<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222"><meta name="generator" content="Hexo 7.3.0">

  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32.ico">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16.ico">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" integrity="sha256-wiz7ZSCn/btzhjKDQBms9Hx4sSeUYsDrTLg7roPstac=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fancyapps-ui/5.0.28/fancybox/fancybox.css" integrity="sha256-6cQIC71/iBIYXFK+0RHAvwmjwWzkWd+r7v/BX3/vZDc=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/pace/1.2.4/themes/green/pace-theme-minimal.css">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/pace/1.2.4/pace.min.js" integrity="sha256-gqd7YTjg/BtfqWSwsJOvndl0Bxc8gFImLEkXQT8+qj0=" crossorigin="anonymous"></script>

<script class="next-config" data-name="main" type="application/json">{"hostname":"sumumm.github.io","root":"/","images":"/images","scheme":"Gemini","darkmode":false,"version":"8.19.2","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":{"enable":true,"style":"mac"},"fold":{"enable":true,"height":300},"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":true,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":true,"transition":{"menu_item":"fadeInDown","post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/search.xml","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false}}</script><script src="/js/config.js"></script>

    <meta name="description" content="本文主要是进程——线程属性的相关笔记，若笔记中有错误或者不合适的地方，欢迎批评指正😃。">
<meta property="og:type" content="article">
<meta property="og:title" content="LV05-02-线程-03-线程属性">
<meta property="og:url" content="https://sumumm.github.io/post/fe0255c0.html">
<meta property="og:site_name" content="苏木">
<meta property="og:description" content="本文主要是进程——线程属性的相关笔记，若笔记中有错误或者不合适的地方，欢迎批评指正😃。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/01%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/01HQ%E8%AF%BE%E7%A8%8B%E4%BD%93%E7%B3%BB/LV05-%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F/LV05-02-%E7%BA%BF%E7%A8%8B-03-%E7%BA%BF%E7%A8%8B%E5%B1%9E%E6%80%A7/img/image-20230305093805949.png">
<meta property="og:image" content="https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/01%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/01HQ%E8%AF%BE%E7%A8%8B%E4%BD%93%E7%B3%BB/LV05-%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F/LV05-02-%E7%BA%BF%E7%A8%8B-03-%E7%BA%BF%E7%A8%8B%E5%B1%9E%E6%80%A7/img/image-20230305140100387.png">
<meta property="article:published_time" content="2023-07-02T13:52:03.000Z">
<meta property="article:modified_time" content="2025-06-13T16:25:56.993Z">
<meta property="article:author" content="苏木">
<meta property="article:tag" content="LV05-操作系统">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/01%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/01HQ%E8%AF%BE%E7%A8%8B%E4%BD%93%E7%B3%BB/LV05-%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F/LV05-02-%E7%BA%BF%E7%A8%8B-03-%E7%BA%BF%E7%A8%8B%E5%B1%9E%E6%80%A7/img/image-20230305093805949.png">


<link rel="canonical" href="https://sumumm.github.io/post/fe0255c0.html">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"https://sumumm.github.io/post/fe0255c0.html","path":"post/fe0255c0.html","title":"LV05-02-线程-03-线程属性"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>LV05-02-线程-03-线程属性 | 苏木</title>
  








    <script src="/js/browser_tools_disable.js"></script>

  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
<!-- hexo injector head_end start --><link rel="stylesheet" href="https://unpkg.com/hexo-next-tags-plus@latest/lib/tag_plus.css" media="defer" onload="this.media='all'"><!-- hexo injector head_end end --></head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <div class="column">
      <header class="header" itemscope itemtype="http://schema.org/WPHeader"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">苏木</p>
      <i class="logo-line"></i>
    </a>
      <p class="site-subtitle" itemprop="description">我的学习之路</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger" aria-label="搜索" role="button">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>苏木的家</a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类页<span class="badge">42</span></a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档页<span class="badge">673</span></a></li><li class="menu-item menu-item-flink"><a href="/flink/" rel="section"><i class="fa fa-link fa-fw"></i>友人帐</a></li><li class="menu-item menu-item-about"><a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于我</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup"><div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close" role="button">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="search-result-container no-result">
  <div class="search-result-icon">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</header>
        
  
  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%B8%80%E3%80%81%E7%BA%BF%E7%A8%8B%E5%B1%9E%E6%80%A7%E5%AF%B9%E8%B1%A1%E7%9A%84%E5%88%9B%E5%BB%BA%E4%B8%8E%E9%94%80%E6%AF%81"><span class="nav-text">一、线程属性对象的创建与销毁</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-pthread-attr-init"><span class="nav-text">1. pthread_attr_init() </span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-1-%E5%87%BD%E6%95%B0%E8%AF%B4%E6%98%8E"><span class="nav-text">1.1 函数说明</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-2-%E4%BD%BF%E7%94%A8%E5%AE%9E%E4%BE%8B"><span class="nav-text">1.2 使用实例</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-pthread-attr-destroy"><span class="nav-text">2. pthread_attr_destroy() </span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#2-1-%E5%87%BD%E6%95%B0%E8%AF%B4%E6%98%8E"><span class="nav-text">2.1 函数说明</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-2-%E4%BD%BF%E7%94%A8%E5%AE%9E%E4%BE%8B"><span class="nav-text">2.2 使用实例</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%BA%8C%E3%80%81%E7%BA%BF%E7%A8%8B%E6%A0%88%E7%9A%84%E5%B1%9E%E6%80%A7"><span class="nav-text">二、线程栈的属性</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-pthread-attr-getstack"><span class="nav-text">1. pthread_attr_getstack()</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-1-%E5%87%BD%E6%95%B0%E8%AF%B4%E6%98%8E-1"><span class="nav-text">1.1 函数说明</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-2-%E4%BD%BF%E7%94%A8%E5%AE%9E%E4%BE%8B-1"><span class="nav-text">1.2 使用实例</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-pthread-attr-setstack"><span class="nav-text">2. pthread_attr_setstack() </span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#2-1-%E5%87%BD%E6%95%B0%E8%AF%B4%E6%98%8E-1"><span class="nav-text">2.1 函数说明</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-2-%E4%BD%BF%E7%94%A8%E5%AE%9E%E4%BE%8B-1"><span class="nav-text">2.2 使用实例</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%B8%89%E3%80%81%E7%BA%BF%E7%A8%8B%E5%88%86%E7%A6%BB%E5%B1%9E%E6%80%A7"><span class="nav-text">三、线程分离属性</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-pthread-attr-setdetachstate"><span class="nav-text">1. pthread_attr_setdetachstate()</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-1-%E5%87%BD%E6%95%B0%E8%AF%B4%E6%98%8E-2"><span class="nav-text">1.1 函数说明</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-2-%E4%BD%BF%E7%94%A8%E5%AE%9E%E4%BE%8B-2"><span class="nav-text">1.2 使用实例</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-pthread-attr-getdetachstate"><span class="nav-text">2. pthread_attr_getdetachstate()</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#2-1-%E5%87%BD%E6%95%B0%E8%AF%B4%E6%98%8E-2"><span class="nav-text">2.1 函数说明 </span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-2-%E4%BD%BF%E7%94%A8%E5%AE%9E%E4%BE%8B-2"><span class="nav-text">2.2 使用实例</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%9B%9B%E3%80%81%E7%BA%BF%E7%A8%8B%E4%BC%98%E5%85%88%E7%BA%A7%E5%B1%9E%E6%80%A7"><span class="nav-text">四、线程优先级属性</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-%E7%BA%BF%E7%A8%8B%E4%BC%98%E5%85%88%E7%BA%A7"><span class="nav-text">1. 线程优先级</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-%E4%B8%89%E7%A7%8D%E8%B0%83%E5%BA%A6%E7%AD%96%E7%95%A5"><span class="nav-text">2. 三种调度策略</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-%E8%B0%83%E5%BA%A6%E7%AD%96%E7%95%A5%E7%9B%B8%E5%85%B3%E5%87%BD%E6%95%B0"><span class="nav-text">3. 调度策略相关函数</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#3-1-pthread-attr-setschedpolicy"><span class="nav-text">3.1 pthread_attr_setschedpolicy()</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#3-1-1-%E5%87%BD%E6%95%B0%E8%AF%B4%E6%98%8E"><span class="nav-text">3.1.1 函数说明</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-1-2-%E4%BD%BF%E7%94%A8%E5%AE%9E%E4%BE%8B"><span class="nav-text">3.1.2 使用实例</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-2-pthread-attr-getschedpolicy"><span class="nav-text">3.2 pthread_attr_getschedpolicy()</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#3-2-1-%E5%87%BD%E6%95%B0%E8%AF%B4%E6%98%8E"><span class="nav-text">3.2.1 函数说明</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-2-2-%E4%BD%BF%E7%94%A8%E5%AE%9E%E4%BE%8B"><span class="nav-text">3.2.2 使用实例</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-3-pthread-attr-setinheritsched"><span class="nav-text">3.3 pthread_attr_setinheritsched()</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#3-3-1-pthread-attr-setinheritsched"><span class="nav-text">3.3.1 pthread_attr_setinheritsched()</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-3-2-%E4%BD%BF%E7%94%A8%E5%AE%9E%E4%BE%8B"><span class="nav-text">3.3.2 使用实例</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-4-pthread-attr-getinheritsched"><span class="nav-text">3.4 pthread_attr_getinheritsched()</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#4-3-4-pthread-attr-getinheritsched"><span class="nav-text">4.3.4 pthread_attr_getinheritsched()</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-3-2-%E4%BD%BF%E7%94%A8%E5%AE%9E%E4%BE%8B-1"><span class="nav-text">3.3.2 使用实例</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-5-pthread-setschedparam"><span class="nav-text">3.5 pthread_setschedparam()</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#3-5-1-%E5%87%BD%E6%95%B0%E8%AF%B4%E6%98%8E"><span class="nav-text">3.5.1 函数说明</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-5-2-%E4%BD%BF%E7%94%A8%E5%AE%9E%E4%BE%8B"><span class="nav-text">3.5.2 使用实例</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-6-pthread-getschedparam"><span class="nav-text">3.6 pthread_getschedparam()</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#3-6-1-%E5%87%BD%E6%95%B0%E8%AF%B4%E6%98%8E"><span class="nav-text">3.6.1 函数说明</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-6-2-%E4%BD%BF%E7%94%A8%E5%AE%9E%E4%BE%8B"><span class="nav-text">3.6.2 使用实例</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-7-pthread-attr-setschedparam"><span class="nav-text">3.7 pthread_attr_setschedparam()</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#3-7-1-%E5%87%BD%E6%95%B0%E8%AF%B4%E6%98%8E"><span class="nav-text">3.7.1 函数说明</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-7-2-%E4%BD%BF%E7%94%A8%E5%AE%9E%E4%BE%8B"><span class="nav-text">3.7.2 使用实例</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-8-pthread-attr-getschedparam"><span class="nav-text">3.8 pthread_attr_getschedparam()</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#3-8-1-%E5%87%BD%E6%95%B0%E8%AF%B4%E6%98%8E"><span class="nav-text">3.8.1 函数说明</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-8-2-%E4%BD%BF%E7%94%A8%E5%AE%9E%E4%BE%8B"><span class="nav-text">3.8.2 使用实例</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-%E4%BC%98%E5%85%88%E7%BA%A7%E8%AE%BE%E7%BD%AE%E7%9B%B8%E5%85%B3%E5%87%BD%E6%95%B0"><span class="nav-text">4. 优先级设置相关函数</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#4-1-sched-get-priority-max"><span class="nav-text">4.1 sched_get_priority_max()</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#4-1-1-%E5%87%BD%E6%95%B0%E8%AF%B4%E6%98%8E"><span class="nav-text">4.1.1 函数说明</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#4-1-2-%E4%BD%BF%E7%94%A8%E5%AE%9E%E4%BE%8B"><span class="nav-text">4.1.2 使用实例</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-2-sched-get-priority-min"><span class="nav-text">4.2 sched_get_priority_min()</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#4-2-1-%E5%87%BD%E6%95%B0%E8%AF%B4%E6%98%8E"><span class="nav-text">4.2.1 函数说明</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#4-2-2-%E4%BD%BF%E7%94%A8%E5%AE%9E%E4%BE%8B"><span class="nav-text">4.2.2 使用实例</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-3-pthread-setschedparam"><span class="nav-text">4.3 pthread_setschedparam()</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-4-pthread-getschedparam"><span class="nav-text">4.4 pthread_getschedparam()</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-5-pthread-attr-setschedparam"><span class="nav-text">4.5 pthread_attr_setschedparam()</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-6-pthread-attr-getschedparam"><span class="nav-text">4.6 pthread_attr_getschedparam()</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#5-CPU%E6%A0%B8%E5%BF%83%E6%95%B0"><span class="nav-text">5. CPU核心数</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#5-1-%E8%99%9A%E6%8B%9F%E6%9C%BA%E8%AE%BE%E7%BD%AE"><span class="nav-text">5.1 虚拟机设置</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5-2-%E6%9F%A5%E7%9C%8BCPU%E7%9A%84%E6%A0%B8%E5%BF%83%E6%95%B0"><span class="nav-text">5.2 查看CPU的核心数</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#5-2-1-%E6%9F%A5%E7%9C%8B%E7%89%A9%E7%90%86CPU%E4%B8%AA%E6%95%B0"><span class="nav-text">5.2.1 查看物理CPU个数</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#5-2-2-%E6%9F%A5%E7%9C%8B%E9%80%BB%E8%BE%91CPU%E4%B8%AA%E6%95%B0"><span class="nav-text">5.2.2 查看逻辑CPU个数</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#5-2-3-%E6%9F%A5%E7%9C%8B%E5%8D%95%E4%B8%AACPU%E6%A0%B8%E6%95%B0"><span class="nav-text">5.2.3 查看单个CPU核数</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#5-2-4-%E7%9B%B4%E6%8E%A5%E6%9F%A5%E7%9C%8BCPU%E6%89%80%E6%9C%89%E4%BF%A1%E6%81%AF"><span class="nav-text">5.2.4 直接查看CPU所有信息</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5-3-C%E8%AF%AD%E8%A8%80%E8%8E%B7%E5%8F%96CPU%E6%A0%B8%E5%BF%83%E6%95%B0"><span class="nav-text">5.3 C语言获取CPU核心数</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#5-3-1-%E5%87%BD%E6%95%B0%E8%AF%B4%E6%98%8E"><span class="nav-text">5.3.1 函数说明</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#5-3-2-%E4%BD%BF%E7%94%A8%E5%AE%9E%E4%BE%8B"><span class="nav-text">5.3.2 使用实例</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#6-%E5%A4%9A%E8%BF%9B%E7%A8%8B%E5%92%8C%E5%A4%9A%E7%BA%BF%E7%A8%8B%E5%9C%A8CPU%E6%A0%B8%E4%B8%8A%E7%9A%84%E8%BF%90%E8%A1%8C"><span class="nav-text">6. 多进程和多线程在CPU核上的运行</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#6-1-taskset%E6%8C%87%E4%BB%A4%E7%BB%91%E5%AE%9A"><span class="nav-text">6.1 taskset指令绑定</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#6-1-1-%E6%B5%8B%E8%AF%95%E7%A8%8B%E5%BA%8F"><span class="nav-text">6.1.1 测试程序</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#6-1-2-%E8%8E%B7%E5%8F%96%E8%BF%9B%E7%A8%8B%E7%9A%84PID"><span class="nav-text">6.1.2 获取进程的PID</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#6-1-3-%E6%9F%A5%E7%9C%8B%E8%BF%9B%E7%A8%8B%E5%BD%93%E5%89%8D%E8%BF%90%E8%A1%8C%E5%9C%A8%E5%93%AA%E4%BA%9BCPU%E4%B8%8A"><span class="nav-text">6.1.3 查看进程当前运行在哪些CPU上</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#6-1-4-%E6%8C%87%E5%AE%9A%E8%BF%9B%E7%A8%8B%E8%BF%90%E8%A1%8C%E5%9C%A8CPU1%E5%92%8C3%E4%B8%8A"><span class="nav-text">6.1.4 指定进程运行在CPU1和3上</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#6-1-5-%E8%BF%90%E8%A1%8C%E7%A8%8B%E5%BA%8F%E6%97%B6%E7%BB%91%E5%AE%9ACPU"><span class="nav-text">6.1.5 运行程序时绑定CPU</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#6-2-C%E8%AF%AD%E8%A8%80%E4%B8%AD%E7%9A%84%E7%BB%91%E5%AE%9A%E7%9B%B8%E5%85%B3%E5%87%BD%E6%95%B0"><span class="nav-text">6.2 C语言中的绑定相关函数</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#6-2-1-sched-setaffinity"><span class="nav-text">6.2.1 sched_setaffinity()</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#6-2-2-sched-getaffinity"><span class="nav-text">6.2.2 sched_getaffinity()</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#6-2-3-pthread-setaffinity-np"><span class="nav-text">6.2.3 pthread_setaffinity_np()</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#6-2-4-pthread-getaffinity-np"><span class="nav-text">6.2.4 pthread_getaffinity_np()</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#6-3-%E7%BB%91%E5%AE%9A%E5%AE%9E%E4%BE%8B"><span class="nav-text">6.3 绑定实例</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#6-3-1-%E4%BD%BF%E7%94%A8%E5%AE%9E%E4%BE%8B1"><span class="nav-text">6.3.1 使用实例1</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#6-3-2-%E4%BD%BF%E7%94%A8%E5%AE%9E%E4%BE%8B2"><span class="nav-text">6.3.2 使用实例2</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#7-%E4%BC%98%E5%85%88%E7%BA%A7%E5%AE%9E%E4%BE%8B"><span class="nav-text">7. 优先级实例</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#7-1-%E4%BF%AE%E6%94%B9linux%E7%9A%84CPU%E6%A0%B8%E5%BF%83%E6%95%B0"><span class="nav-text">7.1 修改linux的CPU核心数</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#7-2-%E6%BC%94%E7%A4%BA%E5%AE%9E%E4%BE%8B"><span class="nav-text">7.2 演示实例</span></a></li></ol></li></ol></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="苏木"
      src="/images/avatar.jpg">
  <p class="site-author-name" itemprop="name">苏木</p>
  <div class="site-description" itemprop="description">莫道桑榆晚，为霞尚满天</div>
</div>
<div class="site-state-wrap animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">673</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">42</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
        <span class="site-state-item-count">43</span>
        <span class="site-state-item-name">标签</span>
      </div>
  </nav>
</div>
  <div class="links-of-author animated">
      <span class="links-of-author-item">
        <a href="https://github.com/sumumm" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;sumumm" rel="noopener me" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
  </div>

        </div>
      </div>
    </div>

    
  </aside>


    </div>

    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://sumumm.github.io/post/fe0255c0.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.jpg">
      <meta itemprop="name" content="苏木">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="苏木">
      <meta itemprop="description" content="莫道桑榆晚，为霞尚满天">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="LV05-02-线程-03-线程属性 | 苏木">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          LV05-02-线程-03-线程属性
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2023-07-02 21:52:03" itemprop="dateCreated datePublished" datetime="2023-07-02T21:52:03+08:00">2023-07-02</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/" itemprop="url" rel="index"><span itemprop="name">嵌入式开发</span></a>
        </span>
          ，
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/01HQ%E8%AF%BE%E7%A8%8B%E4%BD%93%E7%B3%BB/" itemprop="url" rel="index"><span itemprop="name">01HQ课程体系</span></a>
        </span>
          ，
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/01HQ%E8%AF%BE%E7%A8%8B%E4%BD%93%E7%B3%BB/LV05-%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F/" itemprop="url" rel="index"><span itemprop="name">LV05-操作系统</span></a>
        </span>
    </span>

  
    <span class="post-meta-break"></span>
    <span class="post-meta-item" title="本文字数">
      <span class="post-meta-item-icon">
        <i class="far fa-file-word"></i>
      </span>
      <span class="post-meta-item-text">本文字数：</span>
      <span>11k</span>
    </span>
    <span class="post-meta-item" title="阅读时长">
      <span class="post-meta-item-icon">
        <i class="far fa-clock"></i>
      </span>
      <span class="post-meta-item-text">阅读时长 &asymp;</span>
      <span>39 分钟</span>
    </span>
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody"><p>本文主要是进程——线程属性的相关笔记，若笔记中有错误或者不合适的地方，欢迎批评指正😃。</p>
<span id="more"></span>

<!-- Photo: https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/01%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/01HQ%E8%AF%BE%E7%A8%8B%E4%BD%93%E7%B3%BB/LV05-%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F/LV05-02-%E7%BA%BF%E7%A8%8B-03-%E7%BA%BF%E7%A8%8B%E5%B1%9E%E6%80%A7/img/ -->

<details class="folding-tag" blue><summary> 点击查看使用工具及版本 </summary>
              <div class='content'>
              <table>    <tr>        <td align="center" width=150px>Windows</td>        <td align="left">windows11</td>    </tr>    <tr>        <td align="center">Ubuntu</td>        <td align="left">Ubuntu16.04的64位版本</td>      </tr>    <tr>        <td align="center">VMware® Workstation 16 Pro</td>        <td align="left">16.2.3 build-19376536</td>      </tr>    <tr>        <td align="center">SecureCRT</td>        <td align="left">Version 8.7.2 (x64 build 2214)   -   正式版-2020年5月14日</td>      </tr>    <tr>        <td align="center">开发板</td>        <td align="left">正点原子 i.MX6ULL Linux阿尔法开发板</td>      </tr>    <tr>        <td align="center">uboot</td>        <td align="left">NXP官方提供的uboot，NXP提供的版本为uboot-imx-rel_imx_4.1.15_2.1.0_ga(使用的uboot版本为U-Boot 2016.03)</td>      </tr>    <tr>        <td align="center">linux内核</td>        <td align="left">linux-4.15(NXP官方提供)</td>      </tr>    <tr>        <td align="center">STM32开发板</td>        <td align="left">正点原子战舰V3(STM32F103ZET6)</td>      </tr></table>
              </div>
            </details>

<details class="folding-tag" blue><summary> 点击查看本文参考资料 </summary>
              <div class='content'>
              <table>    <tr><td align="center">参考方向  </td><td align="center">参考原文</td></tr>    <tr><td align="left">---</td><td align="left"><a href="" target="_blank">--- <i class="fa fa-external-link-alt"></i> </a></td></tr></table>
              </div>
            </details>

<details class="folding-tag" blue><summary> 点击查看相关文件下载 </summary>
              <div class='content'>
              <table>    <tr>        <td align="center" width=150>---</td>        <td align="left"><a href="" target="_blank">---<i class="fa fa-external-link-alt"></i> </a></td>      </tr></table>
              </div>
            </details>

<p>前边学习线程创建函数的时候我们知道，在创建一个线程的时候我们是可以设置线程的相关属性的，那具体怎么操作呢？在 Linux 下，使用 pthread_attr_t 数据类型定义线程的所有属性，由于多数情况还是默认方式创建，所以这里只做简单的介绍，算是为后边线程分离属性的设置打一个基础吧。</p>
<h1 id="一、线程属性对象的创建与销毁"><a href="#一、线程属性对象的创建与销毁" class="headerlink" title="一、线程属性对象的创建与销毁"></a><font size=3>一、线程属性对象的创建与销毁</font></h1><h2 id="1-pthread-attr-init"><a href="#1-pthread-attr-init" class="headerlink" title="1. pthread_attr_init() "></a><font size=3>1. pthread_attr_init() </font></h2><h3 id="1-1-函数说明"><a href="#1-1-函数说明" class="headerlink" title="1.1 函数说明"></a><font size=3>1.1 函数说明</font></h3><p>在 linux 下可以使用 man pthread_attr_init 命令查看该函数的帮助手册。</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* Compile and link with -pthread. */</span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;pthread.h&gt;</span></span></span><br><span class="line"><span class="type">int</span> <span class="title function_">pthread_attr_init</span><span class="params">(<span class="type">pthread_attr_t</span> *attr)</span>;</span><br></pre></td></tr></table></figure>

<p><strong>【函数说明】</strong>初始化线程的属性。</p>
<p><strong>【函数参数】</strong></p>
<ul>
<li>attr ： pthread_attr_t * 类型，指向需要进行初始化的线程属性对象。</li>
</ul>
<details class="folding-tag" blue><summary> 点击查看 pthread_attr_t 成员 </summary>
              <div class='content'>
              <p>说实话，我没找到这个结构体的定义，下边的在网上搜到的，应该是都差不多，后边找到的话再补充把。</p><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">typedef</span> <span class="class"><span class="keyword">struct</span></span></span><br><span class="line"><span class="class">&#123;</span></span><br><span class="line">	<span class="type">int</span>                detachstate;     <span class="comment">/* 线程的分离状态 */</span></span><br><span class="line">	<span class="type">int</span>                schedpolicy;     <span class="comment">/* 线程调度策略 */</span></span><br><span class="line">	<span class="class"><span class="keyword">struct</span> <span class="title">sched_param</span> <span class="title">schedparam</span>;</span>      <span class="comment">/* 线程的调度参数 */</span></span><br><span class="line">	<span class="type">int</span>                inheritsched;    <span class="comment">/* 线程的继承性 */</span></span><br><span class="line">	<span class="type">int</span>                scope;           <span class="comment">/* 线程的作用域 */</span></span><br><span class="line">	<span class="type">size_t</span>             guardsize;       <span class="comment">/* 线程栈末尾的警戒缓冲区大小 */</span></span><br><span class="line">	<span class="type">int</span>                stackaddr_set;   <span class="comment">/* 线程堆栈设置 */</span></span><br><span class="line">	<span class="type">void</span> *             stackaddr;       <span class="comment">/* 线程栈的位置 */</span></span><br><span class="line">	<span class="type">size_t</span>             stacksize;       <span class="comment">/* 线程栈的大小 */</span></span><br><span class="line">&#125; <span class="type">pthread_attr_t</span>;</span><br></pre></td></tr></table></figure>
              </div>
            </details>

<p><strong>【返回值】</strong> int 类型，成功返回 0 ，失败将返回错误码。</p>
<p><strong>【使用格式】</strong>一般情况下基本使用格式如下：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* 需要包含的头文件 */</span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;pthread.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="comment">/* 至少应该有的语句 */</span></span><br><span class="line"><span class="type">pthread_attr_t</span> attr;</span><br><span class="line">pthread_attr_init(&amp;attr);</span><br></pre></td></tr></table></figure>

<p><strong>【注意事项】</strong> Linux 为 pthread_attr_t 对象的每种属性提供了设置属性的接口以及获取属性的接口，所以我们可以不用关心 pthread_attr_t 结构体内部成员的具体情况。</p>
<h3 id="1-2-使用实例"><a href="#1-2-使用实例" class="headerlink" title="1.2 使用实例"></a><font size=3>1.2 使用实例</font></h3><p>在后边的实例中会有说明。</p>
<h2 id="2-pthread-attr-destroy"><a href="#2-pthread-attr-destroy" class="headerlink" title="2. pthread_attr_destroy() "></a><font size=3>2. pthread_attr_destroy() </font></h2><h3 id="2-1-函数说明"><a href="#2-1-函数说明" class="headerlink" title="2.1 函数说明"></a><font size=3>2.1 函数说明</font></h3><p>在 linux 下可以使用 man pthread_attr_destroy 命令查看该函数的帮助手册。</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* Compile and link with -pthread. */</span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;pthread.h&gt;</span></span></span><br><span class="line"><span class="type">int</span> <span class="title function_">pthread_attr_destroy</span><span class="params">(<span class="type">pthread_attr_t</span> *attr)</span>;</span><br></pre></td></tr></table></figure>

<p><strong>【函数说明】</strong>该函数销毁一个线程属性对象。</p>
<p><strong>【函数参数】</strong></p>
<ul>
<li>attr ： pthread_attr_t * 类型，指向已经进行过初始化的线程属性对象。</li>
</ul>
<p><strong>【返回值】</strong> int 类型，成功返回 0 ，失败将返回错误码。</p>
<p><strong>【使用格式】</strong>一般情况下基本使用格式如下：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* 需要包含的头文件 */</span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;pthread.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="comment">/* 至少应该有的语句 */</span></span><br><span class="line"><span class="type">pthread_attr_t</span> attr;</span><br><span class="line">pthread_attr_destroy(&amp;attr);</span><br></pre></td></tr></table></figure>

<p><strong>【注意事项】</strong>当不再需要一个线程属性对象时，应该使用 pthread_attr_destroy() 函数销毁它，销毁线程属性对象对使用该对象创建的线程没有影响。</p>
<h3 id="2-2-使用实例"><a href="#2-2-使用实例" class="headerlink" title="2.2 使用实例"></a><font size=3>2.2 使用实例</font></h3><p>后边的实例中会有说明。</p>
<h1 id="二、线程栈的属性"><a href="#二、线程栈的属性" class="headerlink" title="二、线程栈的属性"></a><font size=3>二、线程栈的属性</font></h1><p>每个线程都有自己的栈空间， pthread_attr_t 数据结构中定义了栈的起始地址以及栈大小，调用函数 pthread_attr_getstack() 可以获取这些信息，函数 pthread_attr_setstack() 对栈起始地址和栈大小进行设置。</p>
<h2 id="1-pthread-attr-getstack"><a href="#1-pthread-attr-getstack" class="headerlink" title="1. pthread_attr_getstack()"></a><font size=3>1. pthread_attr_getstack()</font></h2><h3 id="1-1-函数说明-1"><a href="#1-1-函数说明-1" class="headerlink" title="1.1 函数说明"></a><font size=3>1.1 函数说明</font></h3><p>在 linux 下可以使用 man pthread_attr_getstack 命令查看该函数的帮助手册。</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* Compile and link with -pthread. */</span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;pthread.h&gt;</span></span></span><br><span class="line"><span class="type">int</span> <span class="title function_">pthread_attr_getstack</span><span class="params">(<span class="type">const</span> <span class="type">pthread_attr_t</span> *attr, <span class="type">void</span> **stackaddr, <span class="type">size_t</span> *stacksize)</span>;</span><br></pre></td></tr></table></figure>

<p><strong>【函数说明】</strong>该函数获取线程创建栈属性 stackaddr 和 stacksize 。</p>
<p><strong>【函数参数】</strong></p>
<ul>
<li><p>attr ： const pthread_attr_t * 类型，参数 attr 指向线程属性对象。</p>
</li>
<li><p>stackaddr ： void ** 类型，是一个二级指针类型，获取的栈的起始地址信息保存在 *stackaddr 中。</p>
</li>
<li><p>stacksize ： size_t * 类型，获取的栈大小信息保存在参数 stacksize 所指向的内存中。</p>
</li>
</ul>
<p><strong>【返回值】</strong> int 类型，成功返回 0 ，失败将返回错误码。</p>
<p><strong>【使用格式】</strong> none </p>
<p><strong>【注意事项】</strong> stackaddr 和 stacksize 描述的堆栈内的所有页面都应该是线程可读写的。</p>
<h3 id="1-2-使用实例-1"><a href="#1-2-使用实例-1" class="headerlink" title="1.2 使用实例"></a><font size=3>1.2 使用实例</font></h3><p>后边的实例会有说明。</p>
<h2 id="2-pthread-attr-setstack"><a href="#2-pthread-attr-setstack" class="headerlink" title="2. pthread_attr_setstack() "></a><font size=3>2. pthread_attr_setstack() </font></h2><h3 id="2-1-函数说明-1"><a href="#2-1-函数说明-1" class="headerlink" title="2.1 函数说明"></a><font size=3>2.1 函数说明</font></h3><p>在 linux 下可以使用 man pthread_attr_setstack 命令查看该函数的帮助手册。</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* Compile and link with -pthread. */</span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;pthread.h&gt;</span></span></span><br><span class="line"><span class="type">int</span> <span class="title function_">pthread_attr_setstack</span><span class="params">(<span class="type">pthread_attr_t</span> *attr, <span class="type">void</span> *stackaddr, <span class="type">size_t</span> stacksize)</span>;</span><br></pre></td></tr></table></figure>

<p><strong>【函数说明】</strong>该函数设置线程创建栈属性 stackaddr 和 stacksize 。</p>
<p><strong>【函数参数】</strong></p>
<ul>
<li><p>attr ： const pthread_attr_t * 类型，参数 attr 指向线程属性对象。</p>
</li>
<li><p>stackaddr ： void * 类型，设置栈起始地址为指定值。</p>
</li>
<li><p>stacksize ： size_t * 类型，：设置栈大小为指定值。</p>
</li>
</ul>
<p><strong>【返回值】</strong> int 类型，成功返回 0 ，失败将返回错误码。</p>
<p><strong>【使用格式】</strong> none </p>
<p><strong>【注意事项】</strong> stackaddr 和 stacksize 描述的堆栈内的所有页面都应该是线程可读写的。</p>
<h3 id="2-2-使用实例-1"><a href="#2-2-使用实例-1" class="headerlink" title="2.2 使用实例"></a><font size=3>2.2 使用实例</font></h3><p>后边的实例会有说明。</p>
<h1 id="三、线程分离属性"><a href="#三、线程分离属性" class="headerlink" title="三、线程分离属性"></a><font size=3>三、线程分离属性</font></h1><h2 id="1-pthread-attr-setdetachstate"><a href="#1-pthread-attr-setdetachstate" class="headerlink" title="1. pthread_attr_setdetachstate()"></a><font size=3>1. pthread_attr_setdetachstate()</font></h2><h3 id="1-1-函数说明-2"><a href="#1-1-函数说明-2" class="headerlink" title="1.1 函数说明"></a><font size=3>1.1 函数说明</font></h3><p>在 linux 下可以使用 man pthread_attr_setdetachstate 命令查看该函数的帮助手册。</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* Compile and link with -pthread. */</span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;pthread.h&gt;</span></span></span><br><span class="line"><span class="type">int</span> <span class="title function_">pthread_attr_setdetachstate</span><span class="params">(<span class="type">pthread_attr_t</span> *attr, <span class="type">int</span> detachstate)</span>;</span><br></pre></td></tr></table></figure>

<p><strong>【函数说明】</strong>该函数设置 detachstate 线程属性（线程的分离状态属性）。</p>
<p><strong>【函数参数】</strong></p>
<ul>
<li>attr ： const pthread_attr_t * 类型，参数 attr 指向线程属性对象。</li>
<li>detachstate ： int 类型， attr 中线程分离状态属性设置为 detachstate 的值。</li>
</ul>
<details class="folding-tag" blue><summary> 点击查看 detachstate 取值情况 </summary>
              <div class='content'>
              <table>    <tr><td align="left" width=150px>PTHREAD_CREATE_DETACHED</td><td align="left">新建线程一开始运行便处于分离状态，以分离状态启动线程，无法被其它线程调用pthread_join()回收，线程结束后由操作系统收回其所占用的资源</td></tr>    <tr><td align="left" width=150px>PTHREAD_CREATE_JOINABLE</td><td align="left">这是detachstate线程属性的默认值，正常启动线程，可以被其它线程获取终止状态信息</td></tr></table>
              </div>
            </details>

<p><strong>【返回值】</strong> int 类型，成功返回 0 ，失败将返回错误码。</p>
<p><strong>【使用格式】</strong></p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* 需要包含的头文件 */</span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;pthread.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="comment">/* 至少应该有的语句 */</span></span><br><span class="line"><span class="type">pthread_attr_t</span> attr;</span><br><span class="line">pthread_attr_init(&amp;attr);</span><br><span class="line">pthread_attr_setdetachstate(&amp;attr, PTHREAD_CREATE_DETACHED);</span><br></pre></td></tr></table></figure>

<p><strong>【注意事项】</strong>如果设置一个线程为分离线程，而这个线程运行又非常快，它很可能在 pthread_create 函数返回之前就终止了，它终止以后就可能将线程号和系统资源移交给其他的线程使用，这样调用 pthread_create 的线程就得到了错误的线程号。要避免这种情况可以采取一定的同步措施。（暂时未遇到，后边遇到了再补充）</p>
<h3 id="1-2-使用实例-2"><a href="#1-2-使用实例-2" class="headerlink" title="1.2 使用实例"></a><font size=3>1.2 使用实例</font></h3><details class="folding-tag" blue><summary> 点击查看实例 </summary>
              <div class='content'>
              <figure class="highlight c"><figcaption><span>test.c</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;stdio.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;pthread.h&gt;</span><span class="comment">/* pthread_create pthread_exit pthread_self pthread_join pthread_detach*/</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;unistd.h&gt;</span> <span class="comment">/* sleep */</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;string.h&gt;</span> <span class="comment">/* strerror */</span></span></span><br><span class="line"></span><br><span class="line"><span class="type">void</span> *<span class="title function_">threadDetach</span><span class="params">(<span class="type">void</span> *arg)</span>;</span><br><span class="line"></span><br><span class="line"><span class="type">int</span> <span class="title function_">main</span><span class="params">(<span class="type">int</span> argc, <span class="type">char</span> *argv[])</span></span><br><span class="line">&#123;</span><br><span class="line">	<span class="type">int</span> ret;</span><br><span class="line">	<span class="type">pthread_t</span> tid;</span><br><span class="line"></span><br><span class="line">	<span class="comment">/* 0. 设置线程分离属性 */</span></span><br><span class="line">	<span class="type">pthread_attr_t</span> attr;</span><br><span class="line">	pthread_attr_init(&amp;attr);<span class="comment">/* 对attr对象进行初始化 */</span></span><br><span class="line">	pthread_attr_setdetachstate(&amp;attr,PTHREAD_CREATE_DETACHED);<span class="comment">/* 设置以分离状态启动线程 */</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">	<span class="comment">/* 1. 创建一个线程 */</span></span><br><span class="line">	ret = pthread_create(&amp;tid, &amp;attr, threadDetach, <span class="literal">NULL</span>);</span><br><span class="line">	<span class="built_in">printf</span>(<span class="string">&quot;This is main thread,ret=%d,tid=%lu\n&quot;</span>, ret, tid);</span><br><span class="line"></span><br><span class="line">	<span class="comment">/* 2. 主线程分离子线程或者在子线程中分离自己 */</span></span><br><span class="line">	sleep(<span class="number">1</span>);</span><br><span class="line">	<span class="comment">/* 3. 分离后进行回收，若分离成功，则会出错 */</span></span><br><span class="line">	ret = pthread_join(tid, <span class="literal">NULL</span>);</span><br><span class="line">	<span class="keyword">if</span>(ret != <span class="number">0</span>)</span><br><span class="line">		<span class="built_in">printf</span>(<span class="string">&quot;pthread_join error: %s\n&quot;</span>, strerror(ret));</span><br><span class="line">	sleep(<span class="number">1</span>);</span><br><span class="line">	<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="type">void</span> *<span class="title function_">threadDetach</span><span class="params">(<span class="type">void</span> *arg)</span></span><br><span class="line">&#123;</span><br><span class="line">	<span class="built_in">printf</span>(<span class="string">&quot;This is a thread test! pid=%d,tid=%lu\n&quot;</span>, getpid(), pthread_self());</span><br><span class="line"></span><br><span class="line">	sleep(<span class="number">1</span>);</span><br><span class="line">	pthread_exit(<span class="string">&quot;thread return!&quot;</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>在终端执行以下命令编译程序：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">gcc test.c -Wall -l pthread # 生成可执行文件 a.out </span><br><span class="line">./a.out # 执行可执行程序</span><br></pre></td></tr></table></figure><p>然后，终端会有以下信息显示：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">This is main thread,ret=0,tid=139921936299584</span><br><span class="line">This is a thread test! pid=8340,tid=139921936299584</span><br><span class="line">pthread_join error: Invalid argument</span><br></pre></td></tr></table></figure>
              </div>
            </details>

<h2 id="2-pthread-attr-getdetachstate"><a href="#2-pthread-attr-getdetachstate" class="headerlink" title="2. pthread_attr_getdetachstate()"></a><font size=3>2. pthread_attr_getdetachstate()</font></h2><h3 id="2-1-函数说明-2"><a href="#2-1-函数说明-2" class="headerlink" title="2.1 函数说明 "></a><font size=3>2.1 函数说明 </font></h3><p>在 linux 下可以使用 man pthread_attr_getdetachstate 命令查看该函数的帮助手册。</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* Compile and link with -pthread. */</span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;pthread.h&gt;</span></span></span><br><span class="line"><span class="type">int</span> <span class="title function_">pthread_attr_getdetachstate</span><span class="params">(<span class="type">const</span> <span class="type">pthread_attr_t</span> *attr, <span class="type">int</span> *detachstate)</span>;</span><br></pre></td></tr></table></figure>

<p><strong>【函数说明】</strong>该函数获取线程创建线程的线程分离状态属性。</p>
<p><strong>【函数参数】</strong></p>
<ul>
<li><p>attr ： const pthread_attr_t * 类型，参数 attr 指向线程属性对象。</p>
</li>
<li><p>detachstate ： int * 类型，获取 attr 中线程分离状态属性，并保存在 detachstate 的所指向的内存空间中。</p>
</li>
</ul>
<p><strong>【返回值】</strong> int 类型，成功返回 0 ，失败将返回错误码。</p>
<p><strong>【使用格式】</strong> none </p>
<p><strong>【注意事项】</strong> none </p>
<h3 id="2-2-使用实例-2"><a href="#2-2-使用实例-2" class="headerlink" title="2.2 使用实例"></a><font size=3>2.2 使用实例</font></h3><p>这个没咋用过，就了解一下吧。</p>
<h1 id="四、线程优先级属性"><a href="#四、线程优先级属性" class="headerlink" title="四、线程优先级属性"></a><font size=3>四、线程优先级属性</font></h1><h2 id="1-线程优先级"><a href="#1-线程优先级" class="headerlink" title="1. 线程优先级"></a><font size=3>1. 线程优先级</font></h2><p>在linux系统中，我们创建的线程时是可以为其指定优先级和调度策略的。在linux系统中的线程分为实时线程和非实时线程，一般创建的线程默认为非实时线程。<strong>所有优先级值在0-99范围内的，都是实时进程，所以这个优先级范围也可以叫做实时进程优先级，而100-139范围内的是非实时进程。</strong></p>
<p>实时线程分<strong>99</strong>个静态优先级，数字越大，优先级越高。在实时线程当中支持抢占调度策略跟轮询调度策略，拥有抢占所有实时线程运行资源的能力，<strong>必须拥有超级用户权限</strong>才能够运行。</p>
<p>对于非实时线程，单位时间中，并没有在乎响应能力的一个线程，里面<strong>只有一个静态优先级0</strong>，也就是在非实时线程中，它是没有静态优先级的概念的，它的所有的执行过程都是由系统自动分配的。非实时线程<strong>只有一个静态优先级</strong>，所以同时非实时线程的任务无法抢占他人的资源，在非实时线程当中只支持其他调度策略 (自动适配的，系统分配的调度策略)不拥有抢占所有运行资源的能力。支持动态优先级系统自适应，从-20到19的动态优先级 (nice值)。</p>
<h2 id="2-三种调度策略"><a href="#2-三种调度策略" class="headerlink" title="2. 三种调度策略"></a><font size=3>2. 三种调度策略</font></h2><ul>
<li>抢占式调度策略，</li>
</ul>
<p>在同一静态优先级的情况下，抢占调度策略的线程一旦运行，便会一直抢占CPU资源，而其他同一优先级的只能一直等到这个抢占式调度策略的线程退出才能被运行到（这个时候的非实时线程会有一小部分资源分配到）。也就是说这种调度策略的线程是先到先服务，一旦占用cpu则一直运行，一直运行直到有更高优先级任务到达或自己放弃。</p>
<ul>
<li>轮询式调度策略</li>
</ul>
<p>在同一静态优先级的情况下，所有线程合理瓜分<strong>时间片</strong>，不会一直抢占CPU资源（这个时候的非实时线程会有一小部分资源分配到）。这个其实就是时间片轮转。当进程的时间片用完，系统将重新分配时间片，并置于就绪队列尾。放在队列尾保证了所有具有相同优先级的RR任务的调度公平</p>
<p>在网上查了一下，时间片长度为100ms，这个倒是有待查证，感觉不会这么长，后边确认了再更新。</p>
<details class="folding-tag" blue><summary> 点击查看时间片 </summary>
              <div class='content'>
              <p>内核在微观上，把CPU的运行时间分成许多分，然后安排给各个进程轮流运行，造成宏观上所有的进程<strong>仿佛</strong>同时在执行，但实际上对于单核CPU来说，同一时刻只会有一个进程运行，线程也是一样。对于双核CPU，实际上最多只能有两个进程在同时运行，另外我们在 top、vmstat 命令里看到的正在运行的进程，并不是真的在占有着CPU。</p>
              </div>
            </details>

<ul>
<li>其他普通式调度策略（分时调度策略）</li>
</ul>
<p>只能作用于非实时线程，由系统自动分配时间片，并目根据运行状态自动分配动态优先级。</p>
<p>【<strong>注意</strong>】<strong>抢占式调度策略和轮询式调度策略只能在实时线程中被设置</strong>，也就是静态优先级1-99的区域内设置，普通非实时线程不能设置。</p>
<h2 id="3-调度策略相关函数"><a href="#3-调度策略相关函数" class="headerlink" title="3. 调度策略相关函数"></a><font size=3>3. 调度策略相关函数</font></h2><h3 id="3-1-pthread-attr-setschedpolicy"><a href="#3-1-pthread-attr-setschedpolicy" class="headerlink" title="3.1 pthread_attr_setschedpolicy()"></a><font size=3>3.1 pthread_attr_setschedpolicy()</font></h3><h4 id="3-1-1-函数说明"><a href="#3-1-1-函数说明" class="headerlink" title="3.1.1 函数说明"></a><font size=3>3.1.1 函数说明</font></h4><p>在 linux 下可以使用 man  pthread_attr_setschedpolicy 命令查看该函数的帮助手册。</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Compile and link with -pthread.</span></span><br><span class="line"></span><br><span class="line"><span class="comment">/* 需包含的头文件 */</span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;pthread.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="comment">/* 函数声明 */</span></span><br><span class="line"><span class="type">int</span> <span class="title function_">pthread_attr_setschedpolicy</span><span class="params">(<span class="type">pthread_attr_t</span> *attr, <span class="type">int</span> policy)</span>;</span><br></pre></td></tr></table></figure>

<p><strong>【函数说明】</strong>该函数用于设置线程的调度策略到线程属性变量中（创建线程时使用）。</p>
<p><strong>【函数参数】</strong></p>
<ul>
<li>attr： pthread_attr_t 类型指针变量，表示线程属性结构体地址。</li>
<li>policy：int 类型变量，表示调度策略，一共有两种，非实时调度策略（SCHED_OTHER）和实时调度策略（SCHED_FIFO, SCHED_RR，其中SCHED_FIFO表示抢占式调度，SCHED_RR是轮询式调度）。</li>
</ul>
<p><strong>【返回值】</strong> int 类型，成功返回0，失败返回一个错误值。</p>
<p><strong>【使用格式】</strong>一般情况下基本使用格式如下：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* 需要包含的头文件 */</span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;pthread.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="comment">/* 至少应该有的语句 */</span></span><br><span class="line"><span class="type">pthread_attr_t</span> attr;</span><br><span class="line">pthread_attr_init(&amp;attr);</span><br><span class="line">pthread_attr_setschedpolicy(&amp;attr, SCHED_RR);</span><br></pre></td></tr></table></figure>

<p><strong>【注意事项】</strong></p>
<p>（1） 一般来说，系统创建线程时，默认的线程都是SCHED_OTHER策略。</p>
<p>（2）为了让pthread_attr_setschedpolicy()在调用pthread_create(创建线程)时生效，调用者必须使用pthread_attr_setinheritsched()将属性对象attr的继承调度器属性设置为PTHREAD_EXPLICIT_SCHED。</p>
<h4 id="3-1-2-使用实例"><a href="#3-1-2-使用实例" class="headerlink" title="3.1.2 使用实例"></a><font size=3>3.1.2 使用实例</font></h4><p>后边会有一个综合测试的实例。</p>
<h3 id="3-2-pthread-attr-getschedpolicy"><a href="#3-2-pthread-attr-getschedpolicy" class="headerlink" title="3.2 pthread_attr_getschedpolicy()"></a><font size=3>3.2 pthread_attr_getschedpolicy()</font></h3><h4 id="3-2-1-函数说明"><a href="#3-2-1-函数说明" class="headerlink" title="3.2.1 函数说明"></a><font size=3>3.2.1 函数说明</font></h4><p>在 linux 下可以使用 man  pthread_attr_getschedpolicy 命令查看该函数的帮助手册。</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Compile and link with -pthread.</span></span><br><span class="line"></span><br><span class="line"><span class="comment">/* 需包含的头文件 */</span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;pthread.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="comment">/* 函数声明 */</span></span><br><span class="line"><span class="type">int</span> <span class="title function_">pthread_attr_getschedpolicy</span><span class="params">(<span class="type">const</span> <span class="type">pthread_attr_t</span> *attr, <span class="type">int</span> *policy)</span>;</span><br></pre></td></tr></table></figure>

<p><strong>【函数说明】</strong>该函数用于获取线程的调度策略到线程属性变量中（创建线程时使用）。</p>
<p><strong>【函数参数】</strong></p>
<ul>
<li>attr： pthread_attr_t 类型指针变量，表示线程属性结构体地址。</li>
<li>policy：int 类型指针变量，表示调度策略，一共有两种，非实时调度策略（SCHED_OTHER）和实时调度策略（SCHED_FIFO, SCHED_RR，其中SCHED_FIFO表示抢占式调度，SCHED_RR是轮询式调度）。</li>
</ul>
<p><strong>【返回值】</strong> int 类型，成功返回0，失败返回一个错误值。</p>
<p><strong>【使用格式】</strong></p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* 需要包含的头文件 */</span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;pthread.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="comment">/* 至少应该有的语句 */</span></span><br><span class="line"><span class="type">pthread_attr_t</span> attr;</span><br><span class="line"><span class="type">int</span> policy;</span><br><span class="line">pthread_attr_init(&amp;attr);</span><br><span class="line">pthread_attr_setschedpolicy(&amp;attr, &amp;policy);</span><br></pre></td></tr></table></figure>

<p><strong>【注意事项】</strong> 一般来说，系统创建线程时，默认的线程都是SCHED_OTHER策略。</p>
<h4 id="3-2-2-使用实例"><a href="#3-2-2-使用实例" class="headerlink" title="3.2.2 使用实例"></a><font size=3>3.2.2 使用实例</font></h4><p>后边会有一个综合测试的实例。</p>
<h3 id="3-3-pthread-attr-setinheritsched"><a href="#3-3-pthread-attr-setinheritsched" class="headerlink" title="3.3 pthread_attr_setinheritsched()"></a><font size=3>3.3 pthread_attr_setinheritsched()</font></h3><h4 id="3-3-1-pthread-attr-setinheritsched"><a href="#3-3-1-pthread-attr-setinheritsched" class="headerlink" title="3.3.1 pthread_attr_setinheritsched()"></a><font size=3>3.3.1 pthread_attr_setinheritsched()</font></h4><p>在 linux 下可以使用 man  pthread_attr_setinheritsched命令查看该函数的帮助手册。</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Compile and link with -pthread.</span></span><br><span class="line"></span><br><span class="line"><span class="comment">/* 需包含的头文件 */</span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;pthread.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="comment">/* 函数声明 */</span></span><br><span class="line"><span class="type">int</span> <span class="title function_">pthread_attr_setinheritsched</span><span class="params">(<span class="type">pthread_attr_t</span> *attr, <span class="type">int</span> inheritsched)</span>;</span><br></pre></td></tr></table></figure>

<p><strong>【函数说明】</strong>该函数用于设置线程的调度策略继承属性到线程属性变量中（创建线程时使用）。一般创建的线程是默认继承父进程的调度策略的，我们再设置线程的优先级是不会生效的，要想使用我们自己设置的调度策略，必须使用此函数设置不继承父进程的调度策略。</p>
<p><strong>【函数参数】</strong></p>
<ul>
<li>attr： pthread_attr_t 类型指针变量，表示线程属性结构体地址。</li>
<li>inheritsched：int 类型变量，表示线程的继承性，一共有两种，PTHREAD_INHERIT_SCHED：使用attr创建的线程从创建的线程继承调度属性，忽略attr中的调度属性；PTHREAD_EXPLICIT_SCHED：使用attr创建的线程从attributes对象指定的值中获取调度属性。在新初始化的线程属性对象中，继承调度器属性的默认设置是PTHREAD_INHERIT_SCHED。</li>
</ul>
<p><strong>【返回值】</strong> int 类型，成功返回0，失败返回一个错误值。</p>
<p><strong>【使用格式】</strong>一般情况下基本使用格式如下：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* 需要包含的头文件 */</span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;pthread.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="comment">/* 至少应该有的语句 */</span></span><br><span class="line"><span class="type">pthread_attr_t</span> attr;</span><br><span class="line">pthread_attr_init(&amp;attr);</span><br><span class="line">pthread_attr_setinheritsched(&amp;attr, PTHREAD_EXPLICIT_SCHED);</span><br></pre></td></tr></table></figure>

<p><strong>【注意事项】</strong></p>
<p>（1） 一般来说，在新初始化的线程属性对象中，继承调度器属性的默认设置是PTHREAD_INHERIT_SCHED。</p>
<p>（2）为了让pthread_attr_setschedpolicy()在调用pthread_create(创建线程)时生效，调用者必须使用pthread_attr_setinheritsched()将属性对象attr的继承调度器属性设置为PTHREAD_EXPLICIT_SCHED。</p>
<h4 id="3-3-2-使用实例"><a href="#3-3-2-使用实例" class="headerlink" title="3.3.2 使用实例"></a><font size=3>3.3.2 使用实例</font></h4><p>后边会有一个综合测试的实例。</p>
<h3 id="3-4-pthread-attr-getinheritsched"><a href="#3-4-pthread-attr-getinheritsched" class="headerlink" title="3.4 pthread_attr_getinheritsched()"></a><font size=3>3.4 pthread_attr_getinheritsched()</font></h3><h4 id="4-3-4-pthread-attr-getinheritsched"><a href="#4-3-4-pthread-attr-getinheritsched" class="headerlink" title="4.3.4 pthread_attr_getinheritsched()"></a><font size=3>4.3.4 pthread_attr_getinheritsched()</font></h4><p>在 linux 下可以使用 man  pthread_attr_getinheritsched命令查看该函数的帮助手册。</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Compile and link with -pthread.</span></span><br><span class="line"></span><br><span class="line"><span class="comment">/* 需包含的头文件 */</span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;pthread.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="comment">/* 函数声明 */</span></span><br><span class="line"><span class="type">int</span> <span class="title function_">pthread_attr_getinheritsched</span><span class="params">(<span class="type">const</span> <span class="type">pthread_attr_t</span> *attr, <span class="type">int</span> *inheritsched)</span>;</span><br></pre></td></tr></table></figure>

<p><strong>【函数说明】</strong>该函数用于获取线程的调度策略继承属性到线程属性变量中（创建线程时使用）。</p>
<p><strong>【函数参数】</strong></p>
<ul>
<li>attr： pthread_attr_t 类型指针变量，表示线程属性结构体地址。</li>
<li>inheritsched：int 类型指针变量，表示线程的继承性，一共有两种，PTHREAD_INHERIT_SCHED：使用attr创建的线程从创建的线程继承调度属性，忽略attr中的调度属性；PTHREAD_EXPLICIT_SCHED：使用attr创建的线程从attributes对象指定的值中获取调度属性。在新初始化的线程属性对象中，继承调度器属性的默认设置是PTHREAD_INHERIT_SCHED。</li>
</ul>
<p><strong>【返回值】</strong> int 类型，成功返回0，失败返回一个错误值。</p>
<p><strong>【使用格式】</strong></p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* 需要包含的头文件 */</span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;pthread.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="comment">/* 至少应该有的语句 */</span></span><br><span class="line"><span class="type">pthread_attr_t</span> attr;</span><br><span class="line"><span class="type">int</span> inheritsched;</span><br><span class="line">pthread_attr_init(&amp;attr);</span><br><span class="line">pthread_attr_getinheritsched(&amp;attr, &amp;inheritsched);</span><br></pre></td></tr></table></figure>

<p><strong>【注意事项】</strong> 一般来说，在新初始化的线程属性对象中，继承调度器属性的默认设置是PTHREAD_INHERIT_SCHED。</p>
<h4 id="3-3-2-使用实例-1"><a href="#3-3-2-使用实例-1" class="headerlink" title="3.3.2 使用实例"></a><font size=3>3.3.2 使用实例</font></h4><p>后边会有一个综合测试的实例。</p>
<h3 id="3-5-pthread-setschedparam"><a href="#3-5-pthread-setschedparam" class="headerlink" title="3.5 pthread_setschedparam()"></a><font size=3>3.5 pthread_setschedparam()</font></h3><h4 id="3-5-1-函数说明"><a href="#3-5-1-函数说明" class="headerlink" title="3.5.1 函数说明"></a><font size=3>3.5.1 函数说明</font></h4><p>在 linux 下可以使用 man  pthread_setschedparam命令查看该函数的帮助手册。</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Compile and link with -pthread.</span></span><br><span class="line"></span><br><span class="line"><span class="comment">/* 需包含的头文件 */</span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;pthread.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="comment">/* 函数声明 */</span></span><br><span class="line"><span class="type">int</span> <span class="title function_">pthread_setschedparam</span><span class="params">(<span class="type">pthread_t</span> thread, <span class="type">int</span> policy, <span class="type">const</span> <span class="keyword">struct</span> sched_param *param)</span>;</span><br></pre></td></tr></table></figure>

<p><strong>【函数说明】</strong>该函数用于设置线程的调度策略和线程的优先级，前边是直接在初始化的时候，通过线程属性设置，这个函数可以在线程创建后，在线程内部设置线程的调度策略，它不受pthread_attr_setinheritsched()函数的影响，也就是说，即便初始化时没有设置不继承父进程调度策略，这里也会将线程配置为我们新设置的调度策略。</p>
<p><strong>【函数参数】</strong></p>
<ul>
<li>thread ： pthread_t 类型变量，表示线程ID，我们可以在线程内部使用pthread_self()函数获取线程ID。</li>
<li>policy ：int 类型变量，表示调度策略，一共有两种，非实时调度策略（SCHED_OTHER）和实时调度策略（SCHED_FIFO, SCHED_RR，其中SCHED_FIFO表示抢占式调度，SCHED_RR是轮询式调度）。</li>
<li>param ：struct sched_param 类型结构体指针变量，表示线程的优先级，它其实只有一个成员，就是sched_priority。</li>
</ul>
<details class="folding-tag" blue><summary> 点击查看 struct sched_param 结构体成员 </summary>
              <div class='content'>
              <figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">sched_param</span> &#123;</span></span><br><span class="line">	<span class="type">int</span> sched_priority;     <span class="comment">/* Scheduling priority */</span></span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
              </div>
            </details>

<p><strong>【返回值】</strong> int 类型，成功返回0，失败返回一个错误值。</p>
<p><strong>【使用格式】</strong></p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* 需要包含的头文件 */</span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;pthread.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="comment">/* 至少应该有的语句 */</span></span><br><span class="line"><span class="type">int</span> policy = SCHED_RR;</span><br><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">sched_param</span> <span class="title">param</span>;</span></span><br><span class="line">param.sched_priority = <span class="number">90</span>;</span><br><span class="line">pthread_setschedparam(pthread_self(), policy, &amp;param);</span><br></pre></td></tr></table></figure>

<p><strong>【注意事项】</strong> 如果pthread_setschedparam()失败，线程的调度策略和参数不会改变。</p>
<h4 id="3-5-2-使用实例"><a href="#3-5-2-使用实例" class="headerlink" title="3.5.2 使用实例"></a><font size=3>3.5.2 使用实例</font></h4><p>后边会有一个综合测试的实例。</p>
<h3 id="3-6-pthread-getschedparam"><a href="#3-6-pthread-getschedparam" class="headerlink" title="3.6 pthread_getschedparam()"></a><font size=3>3.6 pthread_getschedparam()</font></h3><h4 id="3-6-1-函数说明"><a href="#3-6-1-函数说明" class="headerlink" title="3.6.1 函数说明"></a><font size=3>3.6.1 函数说明</font></h4><p>在 linux 下可以使用 man  pthread_getschedparam命令查看该函数的帮助手册。</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Compile and link with -pthread.</span></span><br><span class="line"></span><br><span class="line"><span class="comment">/* 需包含的头文件 */</span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;pthread.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="comment">/* 函数声明 */</span></span><br><span class="line"><span class="type">int</span> <span class="title function_">pthread_getschedparam</span><span class="params">(<span class="type">pthread_t</span> thread, <span class="type">int</span> *policy, <span class="keyword">struct</span> sched_param *param)</span>;</span><br></pre></td></tr></table></figure>

<p><strong>【函数说明】</strong>该函数用于获取线程的调度策略继承属性和线程的优先级，在线程内部使用。</p>
<p><strong>【函数参数】</strong></p>
<ul>
<li>thread ： pthread_t 类型变量，表示线程ID，我们可以在线程内部使用pthread_self()函数获取线程ID。</li>
<li>policy ：int 类型指针变量，表示调度策略，一共有两种，非实时调度策略（SCHED_OTHER）和实时调度策略（SCHED_FIFO, SCHED_RR，其中SCHED_FIFO表示抢占式调度，SCHED_RR是轮询式调度）。</li>
<li>param ：struct sched_param 类型结构体指针变量，表示线程的优先级，它其实只有一个成员，就是sched_priority。</li>
</ul>
<p><strong>【返回值】</strong> int 类型，成功返回0，失败返回一个错误值。</p>
<p><strong>【使用格式】</strong></p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* 需要包含的头文件 */</span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;pthread.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="comment">/* 至少应该有的语句 */</span></span><br><span class="line"><span class="type">int</span> policy;</span><br><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">sched_param</span> <span class="title">param</span>;</span></span><br><span class="line">pthread_getschedparam(pthread_self(), &amp;policy, &amp;param);</span><br></pre></td></tr></table></figure>

<p><strong>【注意事项】</strong> none</p>
<h4 id="3-6-2-使用实例"><a href="#3-6-2-使用实例" class="headerlink" title="3.6.2 使用实例"></a><font size=3>3.6.2 使用实例</font></h4><p>后边会有一个综合测试的实例。</p>
<h3 id="3-7-pthread-attr-setschedparam"><a href="#3-7-pthread-attr-setschedparam" class="headerlink" title="3.7 pthread_attr_setschedparam()"></a><font size=3>3.7 pthread_attr_setschedparam()</font></h3><h4 id="3-7-1-函数说明"><a href="#3-7-1-函数说明" class="headerlink" title="3.7.1 函数说明"></a><font size=3>3.7.1 函数说明</font></h4><p>在 linux 下可以使用 man  pthread_attr_setschedparam命令查看该函数的帮助手册。</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Compile and link with -pthread.</span></span><br><span class="line"></span><br><span class="line"><span class="comment">/* 需包含的头文件 */</span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;pthread.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="comment">/* 函数声明 */</span></span><br><span class="line"><span class="type">int</span> <span class="title function_">pthread_attr_setschedparam</span><span class="params">(<span class="type">pthread_attr_t</span> *attr, <span class="type">const</span> <span class="keyword">struct</span> sched_param *param)</span>;</span><br></pre></td></tr></table></figure>

<p><strong>【函数说明】</strong>该函数用于设置的优先级到线程属性中（线程创建时使用）。</p>
<p><strong>【函数参数】</strong></p>
<ul>
<li>attr： pthread_attr_t 类型指针变量，表示线程属性结构体地址。</li>
<li>param ：struct sched_param 类型结构体指针变量，表示线程的优先级，它其实只有一个成员，就是sched_priority。</li>
</ul>
<details class="folding-tag" blue><summary> 点击查看 struct sched_param 结构体成员 </summary>
              <div class='content'>
              <figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">sched_param</span> &#123;</span></span><br><span class="line">	<span class="type">int</span> sched_priority;     <span class="comment">/* Scheduling priority */</span></span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
              </div>
            </details>

<p><strong>【返回值】</strong> int 类型，成功返回0，失败返回一个错误值。</p>
<p><strong>【使用格式】</strong></p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* 需要包含的头文件 */</span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;pthread.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="comment">/* 至少应该有的语句 */</span></span><br><span class="line"><span class="type">pthread_attr_t</span> attr;</span><br><span class="line">pthread_attr_init(&amp;attr);</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">sched_param</span> <span class="title">param</span>;</span></span><br><span class="line">param.sched_priority = <span class="number">90</span>;</span><br><span class="line">pthread_attr_setschedparam(&amp;attr, &amp;param);</span><br></pre></td></tr></table></figure>

<p><strong>【注意事项】</strong> none</p>
<h4 id="3-7-2-使用实例"><a href="#3-7-2-使用实例" class="headerlink" title="3.7.2 使用实例"></a><font size=3>3.7.2 使用实例</font></h4><p>后边会有一个综合测试的实例。</p>
<h3 id="3-8-pthread-attr-getschedparam"><a href="#3-8-pthread-attr-getschedparam" class="headerlink" title="3.8 pthread_attr_getschedparam()"></a><font size=3>3.8 pthread_attr_getschedparam()</font></h3><h4 id="3-8-1-函数说明"><a href="#3-8-1-函数说明" class="headerlink" title="3.8.1 函数说明"></a><font size=3>3.8.1 函数说明</font></h4><p>在 linux 下可以使用 man  pthread_attr_setschedparam命令查看该函数的帮助手册。</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Compile and link with -pthread.</span></span><br><span class="line"></span><br><span class="line"><span class="comment">/* 需包含的头文件 */</span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;pthread.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="comment">/* 函数声明 */</span></span><br><span class="line"><span class="type">int</span> <span class="title function_">pthread_attr_getschedparam</span><span class="params">(<span class="type">const</span> <span class="type">pthread_attr_t</span> *attr, <span class="keyword">struct</span> sched_param *param)</span>;</span><br></pre></td></tr></table></figure>

<p><strong>【函数说明】</strong>该函数用于获取线程优先级到线程属性中（线程创建时使用）。</p>
<p><strong>【函数参数】</strong></p>
<ul>
<li>attr： pthread_attr_t 类型指针变量，表示线程属性结构体地址。</li>
<li>param ：struct sched_param 类型结构体指针变量，表示线程的优先级，它其实只有一个成员，就是sched_priority。</li>
</ul>
<details class="folding-tag" blue><summary> 点击查看 struct sched_param 结构体成员 </summary>
              <div class='content'>
              <figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">sched_param</span> &#123;</span></span><br><span class="line">	<span class="type">int</span> sched_priority;     <span class="comment">/* Scheduling priority */</span></span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
              </div>
            </details>

<p><strong>【返回值】</strong> int 类型，成功返回0，失败返回一个错误值。</p>
<p><strong>【使用格式】</strong></p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* 需要包含的头文件 */</span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;pthread.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="comment">/* 至少应该有的语句 */</span></span><br><span class="line"><span class="type">pthread_attr_t</span> attr;</span><br><span class="line">pthread_attr_init(&amp;attr);</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">sched_param</span> <span class="title">param</span>;</span></span><br><span class="line">pthread_attr_getschedparam(&amp;attr, &amp;param);</span><br></pre></td></tr></table></figure>

<p><strong>【注意事项】</strong> none</p>
<h4 id="3-8-2-使用实例"><a href="#3-8-2-使用实例" class="headerlink" title="3.8.2 使用实例"></a><font size=3>3.8.2 使用实例</font></h4><p>后边会有一个综合测试的实例。</p>
<h2 id="4-优先级设置相关函数"><a href="#4-优先级设置相关函数" class="headerlink" title="4. 优先级设置相关函数"></a><font size=3>4. 优先级设置相关函数</font></h2><h3 id="4-1-sched-get-priority-max"><a href="#4-1-sched-get-priority-max" class="headerlink" title="4.1 sched_get_priority_max()"></a><font size=3>4.1 sched_get_priority_max()</font></h3><h4 id="4-1-1-函数说明"><a href="#4-1-1-函数说明" class="headerlink" title="4.1.1 函数说明"></a><font size=3>4.1.1 函数说明</font></h4><p>在 linux 下可以使用 man  sched_get_priority_max命令查看该函数的帮助手册。</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* 需包含的头文件 */</span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;sched.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="comment">/* 函数声明 */</span></span><br><span class="line"><span class="type">int</span> <span class="title function_">sched_get_priority_max</span><span class="params">(<span class="type">int</span> policy)</span>;</span><br></pre></td></tr></table></figure>

<p><strong>【函数说明】</strong>该函数用于获取可用于策略识别的调度算法的最大优先级值。</p>
<p><strong>【函数参数】</strong></p>
<ul>
<li>policy：int 类型变量，要获取最大优先级值的调度策略。支持的策略值有:SCHED_FIFO、SCHED_RR、SCHED_OTHER、SCHED_BATCH、SCHED_IDLE和SCHED_DEADLINE。</li>
</ul>
<p><strong>【返回值】</strong> int 类型，成功返回对应调度策略的最大优先级值，失败返回-1，并设置错误号。</p>
<p><strong>【使用格式】</strong>none</p>
<p><strong>【注意事项】</strong>none</p>
<h4 id="4-1-2-使用实例"><a href="#4-1-2-使用实例" class="headerlink" title="4.1.2 使用实例"></a><font size=3>4.1.2 使用实例</font></h4><p>后边会有一个综合测试的实例。</p>
<h3 id="4-2-sched-get-priority-min"><a href="#4-2-sched-get-priority-min" class="headerlink" title="4.2 sched_get_priority_min()"></a><font size=3>4.2 sched_get_priority_min()</font></h3><h4 id="4-2-1-函数说明"><a href="#4-2-1-函数说明" class="headerlink" title="4.2.1 函数说明"></a><font size=3>4.2.1 函数说明</font></h4><p>在 linux 下可以使用 man  sched_get_priority_min命令查看该函数的帮助手册。</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* 需包含的头文件 */</span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;sched.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="comment">/* 函数声明 */</span></span><br><span class="line"><span class="type">int</span> <span class="title function_">sched_get_priority_min</span><span class="params">(<span class="type">int</span> policy)</span>;</span><br></pre></td></tr></table></figure>

<p><strong>【函数说明】</strong>该函数用于获取可用于策略识别的调度算法的最小优先级值。</p>
<p><strong>【函数参数】</strong></p>
<ul>
<li>policy：int 类型变量，要获取最小优先级值的调度策略。支持的策略值有:SCHED_FIFO、SCHED_RR、SCHED_OTHER、SCHED_BATCH、SCHED_IDLE和SCHED_DEADLINE。</li>
</ul>
<p><strong>【返回值】</strong> int 类型，成功返回对应调度策略的最小优先级值，失败返回-1，并设置错误号。</p>
<p><strong>【使用格式】</strong>none</p>
<p><strong>【注意事项】</strong>none</p>
<h4 id="4-2-2-使用实例"><a href="#4-2-2-使用实例" class="headerlink" title="4.2.2 使用实例"></a><font size=3>4.2.2 使用实例</font></h4><p>后边会有一个综合测试的实例。</p>
<h3 id="4-3-pthread-setschedparam"><a href="#4-3-pthread-setschedparam" class="headerlink" title="4.3 pthread_setschedparam()"></a><font size=3>4.3 pthread_setschedparam()</font></h3><p>见上一小节的3.5。</p>
<h3 id="4-4-pthread-getschedparam"><a href="#4-4-pthread-getschedparam" class="headerlink" title="4.4 pthread_getschedparam()"></a><font size=3>4.4 pthread_getschedparam()</font></h3><p>见上一小节的3.6。</p>
<h3 id="4-5-pthread-attr-setschedparam"><a href="#4-5-pthread-attr-setschedparam" class="headerlink" title="4.5 pthread_attr_setschedparam()"></a><font size=3>4.5 pthread_attr_setschedparam()</font></h3><p>见上一小节的3.7。</p>
<h3 id="4-6-pthread-attr-getschedparam"><a href="#4-6-pthread-attr-getschedparam" class="headerlink" title="4.6 pthread_attr_getschedparam()"></a><font size=3>4.6 pthread_attr_getschedparam()</font></h3><p>见上一小节的3.8。</p>
<h2 id="5-CPU核心数"><a href="#5-CPU核心数" class="headerlink" title="5. CPU核心数"></a><font size=3>5. CPU核心数</font></h2><h3 id="5-1-虚拟机设置"><a href="#5-1-虚拟机设置" class="headerlink" title="5.1 虚拟机设置"></a><font size=3>5.1 虚拟机设置</font></h3><p>接下来就是验证一下前边的优先级，但是优先级的验证需要在单个CPU上跑线程，还是先来了解一下怎么查看CPU和操作CPU核的相关内容吧。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">总核数 = 物理CPU个数 X 每颗物理CPU的核数</span><br><span class="line">总逻辑CPU数 = 物理CPU个数 X 每颗物理CPU的核数 X 超线程数</span><br></pre></td></tr></table></figure>

<p>我的下边这些操作都是在虚拟机中进行，我的虚拟机参数如下，这就相当于有2个物理CPU，每个CPU又有2个核心，一共就是有4个逻辑CPU：</p>
<p><img data-src="https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/01%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/01HQ%E8%AF%BE%E7%A8%8B%E4%BD%93%E7%B3%BB/LV05-%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F/LV05-02-%E7%BA%BF%E7%A8%8B-03-%E7%BA%BF%E7%A8%8B%E5%B1%9E%E6%80%A7/img/image-20230305093805949.png" alt="image-20230305093805949"></p>
<h3 id="5-2-查看CPU的核心数"><a href="#5-2-查看CPU的核心数" class="headerlink" title="5.2 查看CPU的核心数"></a><font size=3>5.2 查看CPU的核心数</font></h3><h4 id="5-2-1-查看物理CPU个数"><a href="#5-2-1-查看物理CPU个数" class="headerlink" title="5.2.1 查看物理CPU个数"></a><font size=3>5.2.1 查看物理CPU个数</font></h4><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">cat /proc/cpuinfo| grep &quot;physical id&quot;| sort| uniq| wc -l</span><br><span class="line">cat /proc/cpuinfo | grep &quot;physical id&quot; | uniq</span><br></pre></td></tr></table></figure>

<p>在终端输入以上命令可以看到：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">hk@vm:/$ cat /proc/cpuinfo| grep &quot;physical id&quot;| sort| uniq| wc -l</span><br><span class="line">2</span><br><span class="line"></span><br><span class="line">hk@vm:/$ cat /proc/cpuinfo | grep &quot;physical id&quot; | uniq</span><br><span class="line">physical id	: 0</span><br><span class="line">physical id	: 1</span><br></pre></td></tr></table></figure>

<h4 id="5-2-2-查看逻辑CPU个数"><a href="#5-2-2-查看逻辑CPU个数" class="headerlink" title="5.2.2 查看逻辑CPU个数"></a><font size=3>5.2.2 查看逻辑CPU个数</font></h4><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">cat /proc/cpuinfo| grep &quot;processor&quot;| wc -l</span><br><span class="line">cat /proc/cpuinfo | grep &quot;processor&quot; | uniq</span><br></pre></td></tr></table></figure>

<p>processor：指明每个物理CPU中逻辑处理器信息（序号：0~5表示有6个逻辑CPU）。在终端输入以上命令可以看到：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">hk@vm:/$ cat /proc/cpuinfo| grep <span class="string">&quot;processor&quot;</span>| wc -l</span><br><span class="line"><span class="number">4</span></span><br><span class="line">    </span><br><span class="line">hk@vm:/$ cat /proc/cpuinfo | grep <span class="string">&quot;processor&quot;</span> | uniq</span><br><span class="line">processor	: <span class="number">0</span></span><br><span class="line">processor	: <span class="number">1</span></span><br><span class="line">processor	: <span class="number">2</span></span><br><span class="line">processor	: <span class="number">3</span></span><br></pre></td></tr></table></figure>

<h4 id="5-2-3-查看单个CPU核数"><a href="#5-2-3-查看单个CPU核数" class="headerlink" title="5.2.3 查看单个CPU核数"></a><font size=3>5.2.3 查看单个CPU核数</font></h4><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">cat /proc/cpuinfo | grep &quot;cpu cores&quot; | uniq</span><br></pre></td></tr></table></figure>

<p>cpu cores：指明每颗物理CPU中总核数，在终端输入以上命令可以看到：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">hk@vm:/$ cat /proc/cpuinfo | grep &quot;cpu cores&quot; | uniq</span><br><span class="line">cpu cores	: 2</span><br></pre></td></tr></table></figure>

<h4 id="5-2-4-直接查看CPU所有信息"><a href="#5-2-4-直接查看CPU所有信息" class="headerlink" title="5.2.4 直接查看CPU所有信息"></a><font size=3>5.2.4 直接查看CPU所有信息</font></h4><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">cat /proc/cpuinfo</span><br></pre></td></tr></table></figure>

<p>在终端输入以上命令可以看到：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">太多了，这里就不写了</span><br></pre></td></tr></table></figure>

<h3 id="5-3-C语言获取CPU核心数"><a href="#5-3-C语言获取CPU核心数" class="headerlink" title="5.3 C语言获取CPU核心数"></a><font size=3>5.3 C语言获取CPU核心数</font></h3><p>我们在程序中使用可以使用系统调用 sysconf 获取 cpu 核心数。</p>
<h4 id="5-3-1-函数说明"><a href="#5-3-1-函数说明" class="headerlink" title="5.3.1 函数说明"></a><font size=3>5.3.1 函数说明</font></h4><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* 需要包含的头文件 */</span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;unistd.h&gt;</span></span></span><br><span class="line"><span class="comment">// 返回系统可以使用的核数，但是其值会包括系统中禁用的核的数目，因 此该值并不代表当前系统中可用的核数</span></span><br><span class="line"><span class="type">int</span> <span class="title function_">sysconf</span><span class="params">(_SC_NPROCESSORS_CONF)</span>;</span><br><span class="line"><span class="comment">// 返回值真正的代表了系统当前可用的核数</span></span><br><span class="line"><span class="type">int</span> <span class="title function_">sysconf</span><span class="params">(_SC_NPROCESSORS_ONLN)</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">/* 以下两个函数与上述类似 */</span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;sys/sysinfo.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="type">int</span> <span class="title function_">get_nprocs_conf</span> <span class="params">(<span class="type">void</span>)</span>;<span class="comment">/* 可用核数 */</span></span><br><span class="line"><span class="type">int</span> <span class="title function_">get_nprocs</span> <span class="params">(<span class="type">void</span>)</span>;     <span class="comment">/* 真正的反映了当前可用核数 */</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h4 id="5-3-2-使用实例"><a href="#5-3-2-使用实例" class="headerlink" title="5.3.2 使用实例"></a><font size=3>5.3.2 使用实例</font></h4><details class="folding-tag" blue><summary> 使用实例 </summary>
              <div class='content'>
              <figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;stdio.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;unistd.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;sys/sysinfo.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="type">int</span> <span class="title function_">main</span><span class="params">(<span class="type">int</span> argc, <span class="type">const</span> <span class="type">char</span> *argv[])</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="type">int</span> sc_nprocessor_conf = sysconf(_SC_NPROCESSORS_CONF);</span><br><span class="line">    <span class="type">int</span> sc_nprocessor_onln = sysconf(_SC_NPROCESSORS_ONLN);</span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">&quot;sc_nprocessor_conf:%d\n&quot;</span>, sc_nprocessor_conf);</span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">&quot;sc_nprocessor_onln:%d\n&quot;</span>, sc_nprocessor_onln);</span><br><span class="line"></span><br><span class="line">    <span class="type">int</span> nprocs_conf = get_nprocs_conf();</span><br><span class="line">    <span class="type">int</span> nprocs_onln = get_nprocs();</span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">&quot;nprocs_conf:%d\n&quot;</span>, nprocs_conf);</span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">&quot;nprocs_onln:%d\n&quot;</span>, nprocs_onln);</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>编译执行后如下所示：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">sc_nprocessor_conf:4</span><br><span class="line">sc_nprocessor_onln:4</span><br><span class="line">nprocs_conf:4</span><br><span class="line">nprocs_onln:4</span><br></pre></td></tr></table></figure>
              </div>
            </details>

<h2 id="6-多进程和多线程在CPU核上的运行"><a href="#6-多进程和多线程在CPU核上的运行" class="headerlink" title="6. 多进程和多线程在CPU核上的运行"></a><font size=3>6. 多进程和多线程在CPU核上的运行</font></h2><p>每个 CPU 核运行一个进程的时候，由于每个进程的资源都独立，所以 CPU 核心之间切换的时候无需考虑上下文。每个 CPU 核运行一个线程的时候，有时不同线程之间需要共享资源，所以这些资源必须从 CPU 的一个核心被复制到另外一个核心，这会造成额外的开销。</p>
<h3 id="6-1-taskset指令绑定"><a href="#6-1-taskset指令绑定" class="headerlink" title="6.1 taskset指令绑定"></a><font size=3>6.1 taskset指令绑定</font></h3><h4 id="6-1-1-测试程序"><a href="#6-1-1-测试程序" class="headerlink" title="6.1.1 测试程序"></a><font size=3>6.1.1 测试程序</font></h4><details class="folding-tag" blue><summary> 点击查看测试程序 </summary>
              <div class='content'>
              <p>这里使用进程来进行测试。</p><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;stdio.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;time.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;sys/types.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;unistd.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="type">int</span> <span class="title function_">main</span><span class="params">(<span class="type">int</span> argc, <span class="type">const</span> <span class="type">char</span> *argv[])</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="type">pid_t</span> ppid = getppid();</span><br><span class="line">    <span class="type">pid_t</span> pid = getpid();</span><br><span class="line">    </span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">&quot;ppid %d, pid %d\n&quot;</span>, ppid, pid);</span><br><span class="line">    <span class="keyword">while</span> (<span class="number">1</span>)</span><br><span class="line">    &#123;</span><br><span class="line">        sleep(<span class="number">5</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>使用以下命令编译程序：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">gcc 02_cpu.c -Wall</span><br></pre></td></tr></table></figure><p>我们就会得到一个a.out的可执行文件，我们需要在后台运行这个进程：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">./a.out &amp;</span><br></pre></td></tr></table></figure><p>我们会得到以下输出：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">hk@vm:~/6temp/test$ ./a.out &amp;</span><br><span class="line">[1] 82399</span><br><span class="line">hk@vm:~/6temp/test$ ppid 70526, pid 82399</span><br></pre></td></tr></table></figure>
              </div>
            </details>

<h4 id="6-1-2-获取进程的PID"><a href="#6-1-2-获取进程的PID" class="headerlink" title="6.1.2 获取进程的PID"></a><font size=3>6.1.2 获取进程的PID</font></h4><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">ps -aux | grep &quot;a.out&quot;</span><br></pre></td></tr></table></figure>

<p>我们会得到以下输出信息：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">hk@vm:~/6temp/test$ ps -aux | grep &quot;a.out&quot;</span><br><span class="line">hk        82399  0.0  0.0   4352   732 pts/21   S    12:59   0:00 ./a.out</span><br><span class="line">hk        82450  0.0  0.0  15984   924 pts/21   S+   12:59   0:00 grep --color=auto a.out</span><br></pre></td></tr></table></figure>

<h4 id="6-1-3-查看进程当前运行在哪些CPU上"><a href="#6-1-3-查看进程当前运行在哪些CPU上" class="headerlink" title="6.1.3 查看进程当前运行在哪些CPU上"></a><font size=3>6.1.3 查看进程当前运行在哪些CPU上</font></h4><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">taskset -p 82399</span><br></pre></td></tr></table></figure>

<p>我们会得到以下输出信息：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">hk@vm:~/6temp/test$ taskset -p 82399</span><br><span class="line">pid 82399&#x27;s current affinity mask: f</span><br></pre></td></tr></table></figure>

<p>显示为0x0f（十六进制） 转换为二进制为 1111（二进制），最右起第一个1表示CPU核心0，第二个1表示CPU核心1依次类推。所以进程运行在4个CPU上。</p>
<h4 id="6-1-4-指定进程运行在CPU1和3上"><a href="#6-1-4-指定进程运行在CPU1和3上" class="headerlink" title="6.1.4 指定进程运行在CPU1和3上"></a><font size=3>6.1.4 指定进程运行在CPU1和3上</font></h4><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">taskset -pc 1,3 82399</span><br></pre></td></tr></table></figure>

<p>我们可以看到以下输出：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">hk@vm:~/6temp/test$ taskset -pc 1,3 82399</span><br><span class="line">pid 82399&#x27;s current affinity list: 2</span><br><span class="line">pid 82399&#x27;s new affinity list: 1,3</span><br><span class="line">hk@vm:~/6temp/test$ taskset -p 82399</span><br><span class="line">pid 82399&#x27;s current affinity mask: a</span><br></pre></td></tr></table></figure>

<p>0x0a转化为二进制就是0000 1010，就代表了CPU1和3。</p>
<h4 id="6-1-5-运行程序时绑定CPU"><a href="#6-1-5-运行程序时绑定CPU" class="headerlink" title="6.1.5 运行程序时绑定CPU"></a><font size=3>6.1.5 运行程序时绑定CPU</font></h4><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">taskset -c 3 ./a.out &amp;</span><br></pre></td></tr></table></figure>

<p>可以看到以下信息</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">hk@vm:~/6temp/test$ taskset -c 3 ./a.out &amp;</span><br><span class="line">[1] 82919</span><br><span class="line">hk@vm:~/6temp/test$ ppid 70526, pid 82919</span><br><span class="line"></span><br><span class="line">hk@vm:~/6temp/test$ taskset -p 82919</span><br><span class="line">pid 82919&#x27;s current affinity mask: 8</span><br></pre></td></tr></table></figure>

<p>0x08转化为二进制就是0000 1000，可以看到进程就运行在了CPU3上了。</p>
<h3 id="6-2-C语言中的绑定相关函数"><a href="#6-2-C语言中的绑定相关函数" class="headerlink" title="6.2 C语言中的绑定相关函数"></a><font size=3>6.2 C语言中的绑定相关函数</font></h3><p>CPU Affinity (CPU亲合力)，CPU亲合力就是指在Linux系统中能够将一个或多个进程绑定到一个或多个处理器上运行。一个进程的CPU亲合力掩码决定了该进程将在哪个或哪几个CPU上运行。在一个多处理器系统中，设置CPU亲合力的掩码可能会获得更好的性能。</p>
<p> 一个CPU的亲合力掩码用一个cpu_set_t结构体来表示一个CPU集合,下面的几个宏分别对这个掩码集进行操作:</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">void</span> <span class="title function_">CPU_ZERO</span><span class="params">(<span class="type">cpu_set_t</span> *<span class="built_in">set</span>)</span>;          <span class="comment">// 清空一个集合</span></span><br><span class="line"><span class="type">void</span> <span class="title function_">CPU_SET</span><span class="params">(<span class="type">int</span> cpu, <span class="type">cpu_set_t</span> *<span class="built_in">set</span>)</span>;  <span class="comment">// 将一个给定的CPU号加到一个集合</span></span><br><span class="line"><span class="type">void</span> <span class="title function_">CPU_CLR</span><span class="params">(<span class="type">int</span> cpu, <span class="type">cpu_set_t</span> *<span class="built_in">set</span>)</span>;  <span class="comment">// 将一个给定的CPU号从一个集合中去掉</span></span><br><span class="line"><span class="type">int</span>  <span class="title function_">CPU_ISSET</span><span class="params">(<span class="type">int</span> cpu, <span class="type">cpu_set_t</span> *<span class="built_in">set</span>)</span>;<span class="comment">// 检查一个CPU号是否在这个集合中</span></span><br><span class="line"><span class="type">int</span>  <span class="title function_">CPU_COUNT</span><span class="params">(<span class="type">cpu_set_t</span> *<span class="built_in">set</span>)</span>;         <span class="comment">// 返回集合中包含的CPU数量</span></span><br></pre></td></tr></table></figure>

<p>cpu_set_t 是一个数据类型，具体是啥样的没在内核源码找到，后边找到了再补充吧，反正我们操作的时候都是定义这样一个变量，然后用宏去进行操作。</p>
<h4 id="6-2-1-sched-setaffinity"><a href="#6-2-1-sched-setaffinity" class="headerlink" title="6.2.1 sched_setaffinity()"></a><font size=3>6.2.1 sched_setaffinity()</font></h4><p>在 linux 下可以使用 man  sched_setaffinity命令查看该函数的帮助手册。</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* 需包含的头文件 */</span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> _GNU_SOURCE             <span class="comment">/* See feature_test_macros(7) */</span></span></span><br><span class="line"><span class="comment">// 实际使用的时候加下边的宏</span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> __USE_GNU</span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;sched.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="comment">/* 函数声明 */</span></span><br><span class="line"><span class="type">int</span> <span class="title function_">sched_setaffinity</span><span class="params">(<span class="type">pid_t</span> pid, <span class="type">size_t</span> cpusetsize, <span class="type">const</span> <span class="type">cpu_set_t</span> *mask)</span>;</span><br></pre></td></tr></table></figure>

<p><strong>【函数说明】</strong>该函数用于设置进程号（线程）为pid的进程运行在mask所设定的CPU上。</p>
<p><strong>【函数参数】</strong></p>
<ul>
<li>pid ：pid_t类型变量，表示进程pid，如果pid的值为0,则表示指定的是当前进程</li>
<li>cpusetsize ：size_t类型，是mask所指定的数的长度，通常设定为sizeof(cpu_set_t)。</li>
<li>mask ：cpu_set_t 类型指针变量，CPU亲和力掩码，就是指定在哪几个 CPU 上运行。</li>
</ul>
<p><strong>【返回值】</strong> int 类型，成功返回0，失败返回-1，并设置错误号。</p>
<p><strong>【使用格式】</strong>none</p>
<p><strong>【注意事项】</strong>按照查阅的资料来看，可以设定进程和线程，后边发现有什么问题再更新。</p>
<h4 id="6-2-2-sched-getaffinity"><a href="#6-2-2-sched-getaffinity" class="headerlink" title="6.2.2 sched_getaffinity()"></a><font size=3>6.2.2 sched_getaffinity()</font></h4><p>在 linux 下可以使用 man  sched_getaffinity命令查看该函数的帮助手册。</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* 需包含的头文件 */</span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> _GNU_SOURCE             <span class="comment">/* See feature_test_macros(7) */</span></span></span><br><span class="line"><span class="comment">// 实际使用的时候加下边的宏</span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> __USE_GNU</span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;sched.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="comment">/* 函数声明 */</span></span><br><span class="line"><span class="type">int</span> <span class="title function_">sched_getaffinity</span><span class="params">(<span class="type">pid_t</span> pid, <span class="type">size_t</span> cpusetsize, <span class="type">cpu_set_t</span> *mask)</span>;</span><br></pre></td></tr></table></figure>

<p><strong>【函数说明】</strong>该函数用于获取进程号（线程）为pid所指示的进程的CPU位掩码，并将该掩码返回到mask所指向的结构中。</p>
<p><strong>【函数参数】</strong></p>
<ul>
<li>pid ：pid_t类型变量，表示进程pid，如果pid的值为0,则表示指定的是当前进程</li>
<li>cpusetsize ：size_t类型，是mask所指定的数的长度，通常设定为sizeof(cpu_set_t)。</li>
<li>mask ：cpu_set_t 类型指针变量，CPU亲和力掩码，就是指在哪几个CPU上运行。</li>
</ul>
<p><strong>【返回值】</strong> int 类型，成功返回0，失败返回-1，并设置错误号。</p>
<p><strong>【使用格式】</strong>none</p>
<p><strong>【注意事项】</strong>按照查阅的资料来看，可以设定进程和线程，后边发现有什么问题再更新。</p>
<h4 id="6-2-3-pthread-setaffinity-np"><a href="#6-2-3-pthread-setaffinity-np" class="headerlink" title="6.2.3 pthread_setaffinity_np()"></a><font size=3>6.2.3 pthread_setaffinity_np()</font></h4><p>在 linux 下可以使用 man  pthread_setaffinity_np命令查看该函数的帮助手册。</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* 需包含的头文件 */</span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> _GNU_SOURCE             <span class="comment">/* See feature_test_macros(7) */</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;pthread.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="comment">/* 函数声明 */</span></span><br><span class="line"><span class="type">int</span> <span class="title function_">sched_setaffinity</span><span class="params">(<span class="type">pid_t</span> pid, <span class="type">size_t</span> cpusetsize, <span class="type">const</span> <span class="type">cpu_set_t</span> *mask)</span>;</span><br></pre></td></tr></table></figure>

<p><strong>【函数说明】</strong>该函数用于设置线程为pid的进程运行在mask所设定的CPU上。</p>
<p><strong>【函数参数】</strong></p>
<ul>
<li>pid ：pid_t类型变量，表示线程pid，如果pid的值为0,则表示指定的是当前线程。</li>
<li>cpusetsize ：size_t类型，是mask所指定的数的长度，通常设定为sizeof(cpu_set_t)。</li>
<li>mask ：cpu_set_t 类型指针变量，CPU亲和力掩码，就是指定在哪几个 CPU 上运行。</li>
</ul>
<p><strong>【返回值】</strong> int 类型，成功返回0，失败返回-1，并设置错误号。</p>
<p><strong>【使用格式】</strong>none</p>
<p><strong>【注意事项】</strong>none</p>
<h4 id="6-2-4-pthread-getaffinity-np"><a href="#6-2-4-pthread-getaffinity-np" class="headerlink" title="6.2.4 pthread_getaffinity_np()"></a><font size=3>6.2.4 pthread_getaffinity_np()</font></h4><p>在 linux 下可以使用 man  pthread_getaffinity_np命令查看该函数的帮助手册。</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* 需包含的头文件 */</span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> _GNU_SOURCE             <span class="comment">/* See feature_test_macros(7) */</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;pthread.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="comment">/* 函数声明 */</span></span><br><span class="line"><span class="type">int</span> <span class="title function_">sched_getaffinity</span><span class="params">(<span class="type">pid_t</span> pid, <span class="type">size_t</span> cpusetsize, <span class="type">cpu_set_t</span> *mask)</span>;</span><br></pre></td></tr></table></figure>

<p><strong>【函数说明】</strong>该函数用于获取线程为pid所指示的进程的CPU位掩码，并将该掩码返回到mask所指向的结构中。</p>
<p><strong>【函数参数】</strong></p>
<ul>
<li>pid ：pid_t类型变量，表示线程 pid ，如果 pid 的值为0,则表示指定的是当前线程</li>
<li>cpusetsize ：size_t类型，是mask所指定的数的长度，通常设定为 sizeof(cpu_set_t) 。</li>
<li>mask ：cpu_set_t 类型指针变量，CPU亲和力掩码，就是指在哪几个 CPU 上运行。</li>
</ul>
<p><strong>【返回值】</strong> int 类型，成功返回0，失败返回-1，并设置错误号。</p>
<p><strong>【使用格式】</strong>none</p>
<p><strong>【注意事项】</strong>none</p>
<h3 id="6-3-绑定实例"><a href="#6-3-绑定实例" class="headerlink" title="6.3 绑定实例"></a><font size=3>6.3 绑定实例</font></h3><h4 id="6-3-1-使用实例1"><a href="#6-3-1-使用实例1" class="headerlink" title="6.3.1 使用实例1"></a><font size=3>6.3.1 使用实例1</font></h4><details class="folding-tag" blue><summary> 点击查看详情 </summary>
              <div class='content'>
              <figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;stdlib.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;stdio.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;sys/types.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;sys/sysinfo.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;unistd.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> __USE_GNU</span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;sched.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;ctype.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;string.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;pthread.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> MAX_THREAD_NUM 200 <span class="comment">// 1个CPU内的最多进程数</span></span></span><br><span class="line"></span><br><span class="line"><span class="type">int</span> cpu_cores_num = <span class="number">0</span>;       <span class="comment">// cpu中核数</span></span><br><span class="line"><span class="type">void</span> *<span class="title function_">thread_test</span><span class="params">(<span class="type">void</span> *arg)</span> <span class="comment">// arg  传递线程标号（自己定义）</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="type">cpu_set_t</span> mask; <span class="comment">// CPU核的集合</span></span><br><span class="line">    <span class="type">cpu_set_t</span> get_mask;  <span class="comment">// 获取在集合中的CPU</span></span><br><span class="line">    <span class="type">int</span> *cpu_index = (<span class="type">int</span> *)arg;</span><br><span class="line"></span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">&quot;the thread is:%d\n&quot;</span>, *cpu_index);            <span class="comment">// 显示是第几个线程</span></span><br><span class="line">    CPU_ZERO(&amp;mask);                                     <span class="comment">// 置空</span></span><br><span class="line">    CPU_SET(*cpu_index, &amp;mask);                          <span class="comment">// 设置亲和力值</span></span><br><span class="line">    <span class="keyword">if</span> (sched_setaffinity(<span class="number">0</span>, <span class="keyword">sizeof</span>(mask), &amp;mask) == <span class="number">-1</span>) <span class="comment">// 设置线程CPU亲和力</span></span><br><span class="line">    &#123;</span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">&quot;warning: could not set CPU affinity, continuing...\n&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    CPU_ZERO(&amp;get_mask);</span><br><span class="line">    <span class="keyword">if</span> (sched_getaffinity(<span class="number">0</span>, <span class="keyword">sizeof</span>(get_mask), &amp;get_mask) == <span class="number">-1</span>) <span class="comment">// 获取线程CPU亲和力</span></span><br><span class="line">    &#123;</span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">&quot;warning: cound not get thread affinity, continuing...\n&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">for</span> (<span class="type">int</span> cpu_core_index = <span class="number">0</span>; cpu_core_index &lt; cpu_cores_num; cpu_core_index++)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="keyword">if</span> (CPU_ISSET(cpu_core_index, &amp;get_mask)) <span class="comment">// 判断线程与哪个CPU有亲和力</span></span><br><span class="line">        &#123;</span><br><span class="line">            <span class="built_in">printf</span>(<span class="string">&quot;this thread %d is running processor : %d\n&quot;</span>, cpu_core_index, cpu_core_index);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> <span class="literal">NULL</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="type">int</span> <span class="title function_">main</span><span class="params">(<span class="type">int</span> argc, <span class="type">char</span> *argv[])</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="type">int</span> tid[MAX_THREAD_NUM] = &#123;<span class="number">0</span>&#125;;</span><br><span class="line">    <span class="type">int</span> cpu_core_index = <span class="number">0</span>;</span><br><span class="line">    <span class="type">pthread_t</span> thread[MAX_THREAD_NUM];</span><br><span class="line"></span><br><span class="line">    cpu_cores_num = sysconf(_SC_NPROCESSORS_CONF); <span class="comment">// 获取核数</span></span><br><span class="line">    <span class="keyword">if</span> (cpu_cores_num &gt; MAX_THREAD_NUM)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">&quot;cpu_cores_num of cores[%d] is bigger than MAX_THREAD_NUM[%d]!\n&quot;</span>, cpu_cores_num, MAX_THREAD_NUM);</span><br><span class="line">        <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">&quot;system has %i processor(s). \n&quot;</span>, cpu_cores_num);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span> (cpu_core_index = <span class="number">0</span>; cpu_core_index &lt; cpu_cores_num; cpu_core_index++)</span><br><span class="line">    &#123;</span><br><span class="line">        tid[cpu_core_index] = cpu_core_index;       <span class="comment">// 每个线程必须有个tid[i]</span></span><br><span class="line">        pthread_create(&amp;thread[cpu_core_index], <span class="literal">NULL</span>, thread_test, (<span class="type">void</span> *)&amp;tid[cpu_core_index]);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">for</span> (cpu_core_index = <span class="number">0</span>; cpu_core_index &lt; cpu_cores_num; cpu_core_index++)</span><br><span class="line">    &#123;</span><br><span class="line">        pthread_join(thread[cpu_core_index], <span class="literal">NULL</span>); <span class="comment">// 等待所有的线程结束，线程为死循环所以CTRL+C结束</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>
              </div>
            </details>

<p>通过以下指令编译并运行：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">gcc 02_cpu.c -Wall -lpthread</span><br><span class="line">./a.out</span><br></pre></td></tr></table></figure>

<p>然后可以看到以下输出信息：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">hk@vm:~/6temp/test$ gcc 02_cpu.c -Wall -lpthread</span><br><span class="line">hk@vm:~/6temp/test$ ./a.out </span><br><span class="line">system has 4 processor(s). </span><br><span class="line">the thread is:0</span><br><span class="line">the thread is:3</span><br><span class="line">this thread 0 is running processor : 0</span><br><span class="line">the thread is:2</span><br><span class="line">this thread 3 is running processor : 3</span><br><span class="line">this thread 2 is running processor : 2</span><br><span class="line">the thread is:1</span><br><span class="line">this thread 1 is running processor : 1</span><br></pre></td></tr></table></figure>

<h4 id="6-3-2-使用实例2"><a href="#6-3-2-使用实例2" class="headerlink" title="6.3.2 使用实例2"></a><font size=3>6.3.2 使用实例2</font></h4><details class="folding-tag" blue><summary> 点击查看详情 </summary>
              <div class='content'>
              <figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">define</span> _GNU_SOURCE</span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;pthread.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;stdio.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;stdlib.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;errno.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> handle_error_en(en, msg) \</span></span><br><span class="line"><span class="meta">    do                           \</span></span><br><span class="line"><span class="meta">    &#123;                            \</span></span><br><span class="line"><span class="meta">        errno = en;              \</span></span><br><span class="line"><span class="meta">        perror(msg);             \</span></span><br><span class="line"><span class="meta">        exit(EXIT_FAILURE);      \</span></span><br><span class="line"><span class="meta">    &#125; while (0)</span></span><br><span class="line"></span><br><span class="line"><span class="type">int</span> <span class="title function_">main</span><span class="params">(<span class="type">int</span> argc, <span class="type">char</span> *argv[])</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="type">int</span> err, i;</span><br><span class="line">    <span class="type">cpu_set_t</span> cpuset;</span><br><span class="line"></span><br><span class="line">    <span class="type">pthread_t</span> thread = pthread_self();</span><br><span class="line">    <span class="comment">/* Set affinity mask to include CPUs 0 to 7 */</span></span><br><span class="line"></span><br><span class="line">    CPU_ZERO(&amp;cpuset);</span><br><span class="line">    <span class="keyword">for</span> (i = <span class="number">0</span>; i &lt; <span class="number">8</span>; i++)</span><br><span class="line">    &#123;</span><br><span class="line">        CPU_SET(i, &amp;cpuset);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    err = pthread_setaffinity_np(thread, <span class="keyword">sizeof</span>(<span class="type">cpu_set_t</span>), &amp;cpuset);</span><br><span class="line">    <span class="keyword">if</span> (err != <span class="number">0</span>)</span><br><span class="line">    &#123;</span><br><span class="line">        handle_error_en(err, <span class="string">&quot;pthread_setaffinity_np&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/* Check the actual affinity mask assigned to the thread */</span></span><br><span class="line">    err = pthread_getaffinity_np(thread, <span class="keyword">sizeof</span>(<span class="type">cpu_set_t</span>), &amp;cpuset);</span><br><span class="line">    <span class="keyword">if</span> (err != <span class="number">0</span>)</span><br><span class="line">    &#123;</span><br><span class="line">        handle_error_en(err, <span class="string">&quot;pthread_getaffinity_np&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">&quot;Set returned by pthread_getaffinity_np() contained:\n&quot;</span>);</span><br><span class="line">    <span class="keyword">for</span> (i = <span class="number">0</span>; i &lt; CPU_SETSIZE; i++)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="keyword">if</span> (CPU_ISSET(i, &amp;cpuset))</span><br><span class="line">            <span class="built_in">printf</span>(<span class="string">&quot;CPU %d\n&quot;</span>, i);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="built_in">exit</span>(EXIT_SUCCESS);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>
              </div>
            </details>

<p>通过以下指令编译并运行：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">gcc 02_cpu.c -Wall -lpthread</span><br><span class="line">./a.out</span><br></pre></td></tr></table></figure>

<p>然后可以看到以下输出信息：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">Set returned by pthread_getaffinity_np() contained:</span><br><span class="line">CPU 0</span><br><span class="line">CPU 1</span><br><span class="line">CPU 2</span><br><span class="line">CPU 3</span><br></pre></td></tr></table></figure>

<h2 id="7-优先级实例"><a href="#7-优先级实例" class="headerlink" title="7. 优先级实例"></a><font size=3>7. 优先级实例</font></h2><h3 id="7-1-修改linux的CPU核心数"><a href="#7-1-修改linux的CPU核心数" class="headerlink" title="7.1 修改linux的CPU核心数"></a><font size=3>7.1 修改linux的CPU核心数</font></h3><p>优先级的效果需要在在单个核上才能看出，在这里为了方便测试，我直接将虚拟机的linux改掉，改为1核的，当然也可以用上边的那些函数将相关的线程绑定到同一个核上运行。</p>
<p><img data-src="https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/01%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/01HQ%E8%AF%BE%E7%A8%8B%E4%BD%93%E7%B3%BB/LV05-%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F/LV05-02-%E7%BA%BF%E7%A8%8B-03-%E7%BA%BF%E7%A8%8B%E5%B1%9E%E6%80%A7/img/image-20230305140100387.png" alt="image-20230305140100387"></p>
<ul>
<li>查看修改后的linux核情况</li>
</ul>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">hk@vm:~/6temp/test$ cat /proc/cpuinfo| grep &quot;processor&quot;| wc -l</span><br><span class="line">1</span><br><span class="line">hk@vm:~/6temp/test$ cat /proc/cpuinfo | grep &quot;cpu cores&quot; | uniq</span><br><span class="line">cpu cores       : 1</span><br><span class="line">hk@vm:~/6temp/test$ cat /proc/cpuinfo | grep &quot;physical id&quot; | uniq</span><br><span class="line">physical id     : 0</span><br></pre></td></tr></table></figure>

<h3 id="7-2-演示实例"><a href="#7-2-演示实例" class="headerlink" title="7.2 演示实例"></a><font size=3>7.2 演示实例</font></h3><details class="folding-tag" blue><summary> 点击查看详情 </summary>
              <div class='content'>
              <figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;stdio.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;pthread.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;errno.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;unistd.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;sched.h&gt;</span></span></span><br><span class="line"> </span><br><span class="line"> </span><br><span class="line"><span class="type">void</span> *<span class="title function_">start_routine</span><span class="params">(<span class="type">void</span> *arg)</span></span><br><span class="line">&#123;</span><br><span class="line">	<span class="type">int</span> i, j;</span><br><span class="line"> </span><br><span class="line">	<span class="keyword">while</span>(<span class="number">1</span>)</span><br><span class="line">	&#123;</span><br><span class="line">		<span class="built_in">fprintf</span>(<span class="built_in">stderr</span>, <span class="string">&quot;%c &quot;</span>, *(<span class="type">char</span> *)arg);</span><br><span class="line">		<span class="keyword">for</span>(i=<span class="number">0</span>; i&lt;<span class="number">100000</span>; i++)</span><br><span class="line">			<span class="keyword">for</span>(j=<span class="number">0</span>; j&lt;<span class="number">1000</span>; j++);</span><br><span class="line">	&#125;</span><br><span class="line"> </span><br><span class="line">	pthread_exit(<span class="literal">NULL</span>);</span><br><span class="line">&#125;</span><br><span class="line"> </span><br><span class="line"> </span><br><span class="line"><span class="type">int</span> <span class="title function_">main</span><span class="params">(<span class="type">int</span> argc, <span class="type">char</span> *argv[])</span></span><br><span class="line">&#123;</span><br><span class="line"> </span><br><span class="line">	<span class="type">pthread_t</span> tid1, tid2, tid3;</span><br><span class="line">	<span class="type">pthread_attr_t</span> attr1, attr2;</span><br><span class="line">	<span class="class"><span class="keyword">struct</span> <span class="title">sched_param</span> <span class="title">param1</span>, <span class="title">param2</span>;</span></span><br><span class="line"> </span><br><span class="line">	<span class="comment">/* 线程属性变量的初始化 */</span></span><br><span class="line">	pthread_attr_init(&amp;attr1);</span><br><span class="line">	pthread_attr_init(&amp;attr2);</span><br><span class="line"> </span><br><span class="line"> </span><br><span class="line">	<span class="comment">/* 设置线程是否继承创建者的调度策略 PTHREAD_EXPLICIT_SCHED：不继承才能设置线程的调度策略*/</span></span><br><span class="line">	errno = pthread_attr_setinheritsched(&amp;attr1, PTHREAD_EXPLICIT_SCHED);</span><br><span class="line">	<span class="keyword">if</span>(errno != <span class="number">0</span>)</span><br><span class="line">	&#123;</span><br><span class="line">		perror(<span class="string">&quot;setinherit failed\n&quot;</span>);</span><br><span class="line">		<span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">	&#125;</span><br><span class="line"> </span><br><span class="line">	<span class="comment">/* 设置线程是否继承创建者的调度策略 PTHREAD_EXPLICIT_SCHED：不继承才能设置线程的调度策略*/</span></span><br><span class="line">	errno = pthread_attr_setinheritsched(&amp;attr2, PTHREAD_EXPLICIT_SCHED);</span><br><span class="line">	<span class="keyword">if</span>(errno != <span class="number">0</span>)</span><br><span class="line">	&#123;</span><br><span class="line">		perror(<span class="string">&quot;setinherit failed\n&quot;</span>);</span><br><span class="line">		<span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">	&#125;</span><br><span class="line"> </span><br><span class="line">	<span class="comment">/* 设置线程的调度策略：SCHED_FIFO：抢占性调度; SCHED_RR：轮寻式调度；SCHED_OTHER：非实时线程调度策略*/</span></span><br><span class="line">	errno = pthread_attr_setschedpolicy(&amp;attr1, SCHED_RR);</span><br><span class="line">	<span class="keyword">if</span>(errno != <span class="number">0</span>)</span><br><span class="line">	&#123;</span><br><span class="line">		perror(<span class="string">&quot;setpolicy failed\n&quot;</span>);</span><br><span class="line">		<span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">	&#125;</span><br><span class="line"> </span><br><span class="line">	errno = pthread_attr_setschedpolicy(&amp;attr2, SCHED_RR);</span><br><span class="line">	<span class="keyword">if</span>(errno != <span class="number">0</span>)</span><br><span class="line">	&#123;</span><br><span class="line">		perror(<span class="string">&quot;setpolicy failed\n&quot;</span>);</span><br><span class="line">		<span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">	&#125;</span><br><span class="line"> </span><br><span class="line">	<span class="comment">//设置优先级的级别</span></span><br><span class="line">	param1.sched_priority = <span class="number">1</span>;</span><br><span class="line">	param2.sched_priority = <span class="number">1</span>;</span><br><span class="line">	</span><br><span class="line">	<span class="comment">//查看抢占性调度策略的最小跟最大静态优先级的值是多少</span></span><br><span class="line">	<span class="built_in">printf</span>(<span class="string">&quot;min=%d, max=%d\n&quot;</span>, sched_get_priority_min(SCHED_FIFO), sched_get_priority_max(SCHED_FIFO));</span><br><span class="line"> </span><br><span class="line"> </span><br><span class="line">	<span class="comment">/* 设置线程静态优先级 */</span></span><br><span class="line">	errno = pthread_attr_setschedparam(&amp;attr1, &amp;param1);</span><br><span class="line">	<span class="keyword">if</span>(errno != <span class="number">0</span>)</span><br><span class="line">	&#123;</span><br><span class="line">		perror(<span class="string">&quot;setparam failed\n&quot;</span>);</span><br><span class="line">		<span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">	&#125;</span><br><span class="line"> </span><br><span class="line">	errno = pthread_attr_setschedparam(&amp;attr2, &amp;param2);</span><br><span class="line">	<span class="keyword">if</span>(errno != <span class="number">0</span>)</span><br><span class="line">	&#123;</span><br><span class="line">		perror(<span class="string">&quot;setparam failed\n&quot;</span>);</span><br><span class="line">		<span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">	&#125;</span><br><span class="line"> </span><br><span class="line"><span class="comment">/* 创建三个测试线程 */</span></span><br><span class="line">    <span class="comment">/* 线程1，优先级1 */</span></span><br><span class="line">	errno = pthread_create(&amp;tid1, &amp;attr1, start_routine, (<span class="type">void</span> *)<span class="string">&quot;1&quot;</span>);</span><br><span class="line">	<span class="keyword">if</span>(errno != <span class="number">0</span>)</span><br><span class="line">	&#123;</span><br><span class="line">		perror(<span class="string">&quot;create thread 1 failed\n&quot;</span>);</span><br><span class="line">		<span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">	&#125;</span><br><span class="line">    <span class="comment">/* 线程2，优先级1 */</span></span><br><span class="line">	errno = pthread_create(&amp;tid2, &amp;attr2, start_routine, (<span class="type">void</span> *)<span class="string">&quot;2&quot;</span>);</span><br><span class="line">	<span class="keyword">if</span>(errno != <span class="number">0</span>)</span><br><span class="line">	&#123;</span><br><span class="line">		perror(<span class="string">&quot;create thread 2 failed\n&quot;</span>);</span><br><span class="line">		<span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">	&#125;</span><br><span class="line">    <span class="comment">/* 线程3，非实时线程，静态优先级0 */</span></span><br><span class="line">	errno = pthread_create(&amp;tid3, <span class="literal">NULL</span>, start_routine, (<span class="type">void</span> *)<span class="string">&quot;3&quot;</span>);</span><br><span class="line">	<span class="keyword">if</span>(errno != <span class="number">0</span>)</span><br><span class="line">	&#123;</span><br><span class="line">		perror(<span class="string">&quot;create thread 3 failed\n&quot;</span>);</span><br><span class="line">		<span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">	&#125;</span><br><span class="line"> </span><br><span class="line">	pthread_join(tid1, <span class="literal">NULL</span>);</span><br><span class="line">	pthread_join(tid2, <span class="literal">NULL</span>);</span><br><span class="line">	pthread_join(tid3, <span class="literal">NULL</span>);</span><br><span class="line"> </span><br><span class="line">	pthread_attr_destroy(&amp;attr1);</span><br><span class="line">	pthread_attr_destroy(&amp;attr2);</span><br><span class="line"> </span><br><span class="line">	<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
              </div>
            </details>

<p>我们编译并执行程序：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">hk@vm:~/6temp/test$ gcc 02_cpu.c -Wall -lpthread</span><br><span class="line">hk@vm:~/6temp/test$ ./a.out </span><br><span class="line">min=1, max=99</span><br><span class="line">create thread 1 failed</span><br><span class="line">: Operation not permitted</span><br></pre></td></tr></table></figure>

<p>可以看到我们没有权限修改优先级，必须要有管理员权限才可以。</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">hk@vm:~/6temp/test$ sudo ./a.out </span><br></pre></td></tr></table></figure>

<ul>
<li>设置优先级的两个线程均为 SCHED_FIFO时</li>
</ul>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">hk@vm:~/6temp/test$ gcc 02_cpu.c -Wall -lpthread</span><br><span class="line">hk@vm:~/6temp/test$ sudo ./a.out </span><br><span class="line">min=1, max=99</span><br><span class="line">1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 3 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 3 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 3 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 3 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 3 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 3 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 3 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 3 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 ^C</span><br></pre></td></tr></table></figure>

<p>会发现线程2根本就没有执行过，这是因为它俩优先级一样，但是线程1先被创建，先运行，一旦运行就会一直抢占资源，线程2优先级又和线程1一样，这样就导致线程2根本没有执行过。同时会发现，即便线程3是非实时线程，也会得到执行的机会，虽然很少。</p>
<ul>
<li>设置优先级的两个线程均为 SCHED_RR时</li>
</ul>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">hk@vm:~/6temp/test$ gcc 02_cpu.c -Wall -lpthread</span><br><span class="line">hk@vm:~/6temp/test$ sudo ./a.out </span><br><span class="line">min=1, max=99</span><br><span class="line">1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 3 1 2 2 2 1 1 2 2 1 1 1 2 2 1 1 2 2 2 1 1 2 2 3 1 1 1 2 2 1 1 2 2 2 1 1 2 2 1 1 1 2 2 1 1 2 3 2 2 1 1 2 2 1 1 1 2 2 1 1 2 2 1 1 2 2 2 1 1 3 1 2 2 1 1 2 2 1 1 2 2 2 1 1 1 2 2 1 1 2 2 1 3 1 2 2 2 1 1 1 2 2 1 1 2 2 1 1 2 2 2 1 1 2 2 1 1 1 2 2 1 1 2 2 2 1 1 2 2 1 1 1 2 2 1 1 2 3 2 2 1 1 2 2 1 1 1 2 2 1 1 2 2 2 1 1 2 2 1 1 ^C</span><br></pre></td></tr></table></figure>

<p>会发现，当线程2开始执行后，基本就是线程1和2执行次数相当，线程3也会执行，但是也会很少，这就是线程的优先级问题。</p>

    </div>

    
    
    

    <footer class="post-footer">




    <div>
        
            <div style="text-align:center;color: #ccc;font-size:14px;">
            ----------本文结束
            <i class="fas fa-fan fa-spin" style="color: #FF1493; font-size: 1rem"></i>
            感谢您的阅读----------
            </div>
        
    </div>





  
  <div class="my_post_copyright"> 
    <p><span>文章标题:</span><a href="/post/fe0255c0.html">LV05-02-线程-03-线程属性</a></p>
    <p><span>文章作者:</span><a href="/" title="欢迎访问 《苏木》 的学习笔记">苏木</a></p>
    <p><span>发布时间:</span>2023年07月02日 - 21:52</p>
    <p><span>最后更新:</span>2025年06月14日 - 00:25</p>
    <p><span>原始链接:</span><a href="/post/fe0255c0.html" title="LV05-02-线程-03-线程属性">https://sumumm.github.io/post/fe0255c0.html</a></p>
    <p><span>许可协议:</span><i class="fab fa-creative-commons"></i> <a rel="license" href= "https://creativecommons.org/licenses/by-nc-nd/4.0/" target="_blank" title="Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0)">署名-非商业性使用-禁止演绎 4.0 国际</a> 转载请保留原文链接及作者。</p>  
  </div>
  


          <div class="post-tags">
              <a href="/tags/LV05-%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F/" rel="tag"><i class="fa fa-tag"></i> LV05-操作系统</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/post/744eefdb.html" rel="prev" title="LV05-02-线程-04-线程分离">
                  <i class="fa fa-angle-left"></i> LV05-02-线程-04-线程分离
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/post/4e20d76.html" rel="next" title="LV05-02-线程-02-线程的创建与回收">
                  LV05-02-线程-02-线程的创建与回收 <i class="fa fa-angle-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">

  <div class="copyright">
    &copy; 2017 – 
    <span itemprop="copyrightYear">2025</span>
    <span class="with-love">
      <i class="fa fa-heart"></i>
    </span>
    <span class="author" itemprop="copyrightHolder">苏木</span>
  </div>
<div class="wordcount">
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-line"></i>
    </span>
      <span>站点总字数：</span>
    <span title="站点总字数">3.7m</span>
  </span>
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
      <span>站点阅读时长 &asymp;</span>
    <span title="站点阅读时长">225:26</span>
  </span>
</div>




    <span id="sitetime"></span>
    <script defer language=javascript>
        function siteTime()
        {
            window.setTimeout("siteTime()", 1000);
            var seconds = 1000;
            var minutes = seconds * 60;
            var hours = minutes * 60;
            var days = hours * 24;
            var years = days * 365;
            var today = new Date();
            var todayYear = today.getFullYear();
            var todayMonth = today.getMonth()+1;
            var todayDate = today.getDate();
            var todayHour = today.getHours();
            var todayMinute = today.getMinutes();
            var todaySecond = today.getSeconds();
            /*==================================================
            Date.UTC() -- 返回date对象距世界标准时间(UTC)1970年1月1日午夜之间的毫秒数(时间戳)
            year        - 作为date对象的年份，为4位年份值
            month       - 0-11之间的整数，做为date对象的月份
            day         - 1-31之间的整数，做为date对象的天数
            hours       - 0(午夜24点)-23之间的整数，做为date对象的小时数
            minutes     - 0-59之间的整数，做为date对象的分钟数
            seconds     - 0-59之间的整数，做为date对象的秒数
            microseconds - 0-999之间的整数，做为date对象的毫秒数
            ==================================================*/
            var t1 = Date.UTC(2017, 
                              5, 
                              19, 
                              0, 
                              0, 
                              0); //北京时间
            var t2 = Date.UTC(todayYear,todayMonth,todayDate,todayHour,todayMinute,todaySecond);
            var diff = t2-t1;
            var diffYears = Math.floor(diff/years);
            var diffDays = Math.floor((diff/days)-diffYears*365);
            var diffHours = Math.floor((diff-(diffYears*365+diffDays)*days)/hours);
            var diffMinutes = Math.floor((diff-(diffYears*365+diffDays)*days-diffHours*hours)/minutes);
            var diffSeconds = Math.floor((diff-(diffYears*365+diffDays)*days-diffHours*hours-diffMinutes*minutes)/seconds);
            document.getElementById("sitetime").innerHTML="已在这里 "+diffYears+" 年 "+diffDays+" 天 "+diffHours+" 小时 "+diffMinutes+" 分钟 "+diffSeconds+" 秒";
        }
        siteTime();
    </script>



    </div>
  </footer>

  
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up fa-lg"></i>
    <span>0%</span>
  </div>
  <div class="reading-progress-bar"></div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/next-theme-pjax/0.6.0/pjax.min.js" integrity="sha256-vxLn1tSKWD4dqbMRyv940UYw4sXgMtYcK6reefzZrao=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/fancyapps-ui/5.0.28/fancybox/fancybox.umd.js" integrity="sha256-ytMJGN3toR+a84u7g7NuHm91VIR06Q41kMWDr2pq7Zo=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/lozad.js/1.16.0/lozad.min.js" integrity="sha256-mOFREFhqmHeQbXpK2lp4nA3qooVgACfh88fpJftLBbc=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/next-boot.js"></script><script src="/js/pjax.js"></script>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/hexo-generator-searchdb/1.4.1/search.js" integrity="sha256-1kfA5uHPf65M5cphT2dvymhkuyHPQp5A53EGZOnOLmc=" crossorigin="anonymous"></script>
<script src="/js/third-party/search/local-search.js"></script>




  <script src="/js/third-party/fancybox.js"></script>

  <script src="/js/third-party/pace.js"></script>


  




  

  <script class="next-config" data-name="enableMath" type="application/json">true</script><script class="next-config" data-name="mathjax" type="application/json">{"enable":true,"tags":"none","js":{"url":"https://cdnjs.cloudflare.com/ajax/libs/mathjax/3.2.2/es5/tex-mml-chtml.js","integrity":"sha256-MASABpB4tYktI2Oitl4t+78w/lyA+D7b/s9GEP0JOGI="}}</script>
<script src="/js/third-party/math/mathjax.js"></script>


 
        <div id="click-show-text"
            data-mobile = false
            data-text = 富强,民主,文明,和谐,自由,平等,公正,法制,爱国,敬业,诚信,友善
            data-fontsize = 15px
            data-random= false>
        </div>
       

      
        <script async src=https://cdn.jsdelivr.net/npm/hexo-next-mouse-effect@latest/click/showText.js></script>
      

      
    




    <script async src="/js/fancybox_param.js"></script>





<!-- APlayer本体 -->



</body>
</html>
